使用JWT實現鑑權完成帶token訪問資源
阿新 • • 發佈:2021-09-17
第一步 先安裝相應的Nuget包
第二步 現在startup中新增認證服務
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region 直接jwt驗證 var Issurer = "JWTBearer.Auth"; //發行人 var Audience = "api.auth"; //受眾人 var secretCredentials = "q2xiARx$4x3TKqBJ"; //金鑰 //配置認證服務 services.AddAuthentication(x => { //預設身份驗證方案 Bearer token x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //預設挑戰方案 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters { //是否驗證發行人 ValidateIssuer = true, ValidIssuer = Issurer,//發行人 //是否驗證受眾人 ValidateAudience = true, ValidAudience = Audience,//受眾人 //是否驗證金鑰 ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretCredentials)), ValidateLifetime = true, //驗證生命週期 RequireExpirationTime = true, //過期時間 }; }); #endregion }
第三步 applicationbuilder app中使用
//1.先開啟認證
app.UseAuthentication();
//2.再開啟授權
app.UseAuthorization();
第四步 新建一個授權控制器 裡面token生成的內容與在startup中注入的內容一致(發行人 受眾人 過期時間 金鑰等等)
[Route("api/[controller]")] [ApiController] public class AuthController : ControllerBase { [AllowAnonymous] [HttpGet, Route("GetToken")] public IActionResult GetToken() { try { //定義發行人issuer string iss = "JWTBearer.Auth"; //定義受眾人audience string aud = "api.auth"; //定義許多種的宣告Claim,資訊儲存部分,Claims的實體一般包含使用者和一些元資料 IEnumerable<Claim> claims = new Claim[] { new Claim(JwtClaimTypes.Id,"1"), new Claim(JwtClaimTypes.Name,"i3yuan"), }; //notBefore 生效時間 // long nbf =new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds(); var nbf = DateTime.UtcNow; //expires //過期時間 // long Exp = new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds(); var Exp = DateTime.UtcNow.AddSeconds(1000); //signingCredentials 簽名憑證 密碼 string sign = "q2xiARx$4x3TKqBJ"; //SecurityKey 的長度必須 大於等於 16個字元 //字串轉為位元組串 var secret = Encoding.UTF8.GetBytes(sign); //是根據預先的二進位制位元組陣列生成一個安全祕鑰,說白了就是密碼 var key = new SymmetricSecurityKey(secret); //生成一個Token證書 第一個引數密碼,第二個引數是編碼方式 var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable<Claim> claims = null, DateTime? notBefore = null, DateTime? expires = null, SigningCredentials signingCredentials = null); var jwt = new JwtSecurityToken(issuer: iss, audience: aud, claims: claims, notBefore: nbf, expires: Exp, signingCredentials: signcreds); //建立一個JwtSecurityTokenHandler類,用來後續操作 var JwtHander = new JwtSecurityTokenHandler(); //建立一個token var token = JwtHander.WriteToken(jwt); return Ok(new { access_token = token, token_type = "Bearer", }); } catch (Exception ex) { throw; } } }