
先安装jwt包
Microsoft.AspNetCore.Authentication.JwtBearer;
配置类JwtConfig
public class JwtConfig { public string Key { get; set; } //key public int expres { get; set; } //过期时间(单位秒) public string Issuer { get; set; } public string Audience { get; set; } } //注入配置类 builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JWT")); //配置文件appsettings.json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "JWT": { "Key": "sasdjfakljdssfjanjkdsjiio3*98sdkjndfkandsf111", "expres": "3" } }
创建token
//依赖注入 private readonly IOptionsSnapshot<JwtConfig> jwtconfig; public Demo3Controller(IOptionsSnapshot<JwtConfig> jwtconfig) { this.jwtconfig = jwtconfig; } public string CreateToken() { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, "admin")); claims.Add(new Claim(ClaimTypes.NameIdentifier, "1080")); DateTime expres = DateTime.Now.AddSeconds(jwtconfig.Value.expres); Console.WriteLine($"过期时间{expres}"); byte[] secbyse = Encoding.UTF8.GetBytes(jwtconfig.Value.Key); var secKey = new SymmetricSecurityKey(secbyse); var credetials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256); var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expres, signingCredentials: credetials); string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor); return jwt; }
Program.cs验证token
//配置Jwt密钥 builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JWT")); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt => { var JwtOtp = builder.Configuration.GetSection("JWT").Get<JwtConfig>(); byte[] keybase = Encoding.UTF8.GetBytes(JwtOtp.Key); var seckey = new SymmetricSecurityKey(keybase); opt.TokenValidationParameters = new() { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = seckey, }; opt.Events = new JwtBearerEvents { //权限验证失败后执行 OnChallenge = context => { //终止默认的返回结果 context.HandleResponse(); string token = context.Request.Headers["Authorization"]; var result = JsonConvert.SerializeObject(new { code = 401, message = "登录过期" }); if (string.IsNullOrEmpty(token)) { result = JsonConvert.SerializeObject(new { code = 401, message = "token不能为空" }); context.Response.ContentType = "application/json"; //验证失败返回401 context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(result); return Task.FromResult(result); } try { JwtSecurityTokenHandler tokenheader = new(); ClaimsPrincipal claimsPrincipal = tokenheader.ValidateToken(token, opt.TokenValidationParameters, out SecurityToken securityToken); } catch (SecurityTokenExpiredException) { result = JsonConvert.SerializeObject(new { code = 401, message = "登录已过期" }); context.Response.ContentType = "application/json"; //验证失败返回401 context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(result); return Task.FromResult(result); } catch (Exception ex) { Console.WriteLine(ex); result = JsonConvert.SerializeObject(new { code = 402, message = "token令牌无效" }); context.Response.ContentType = "application/json"; //验证失败返回401 context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(result); return Task.FromResult(result); } context.Response.ContentType = "application/json"; //验证失败返回401 context.Response.StatusCode = StatusCodes.Status200OK; context.Response.WriteAsync(result); return Task.FromResult(result); } }; }); app.UseAuthentication();//jwt中间件
评价