JwtBearer简介
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer2)新建一个JwtConfig类,用了存储token相关数据。
public class JwtConfig{public string Key { get; set; } //keypublic int Expres { get; set; } //过期时间(单位秒)public string Issuer { get; set; }public string Audience { get; set; }}
3)、在appsettings.json中配置jwt密钥
//配置文件appsettings.json{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*",//JWT的配置内容"JWT": {//key必须有足够的长度"Key": "asfasfdflj134aanjkdsjiio1232sdasdfdfkandsf12","expres": "3","Issuer": "https://localhost:7201","Audience": "https://localhost:7201",}}
4)在program.cs文件注入JwtBearer
//注入配置类builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JWT"));
5)新建一个类,专门创建token
//依赖注入private readonly IOptionsSnapshot<JwtConfig> jwtconfig;public Demo3Controller(IOptionsSnapshot<JwtConfig> jwtconfig){this.jwtconfig = jwtconfig;}public string CreateToken(){// 创建声明列表,即 Token 中携带的信息List<Claim> claims = new List<Claim>();claims.Add(new Claim(ClaimTypes.Name, "admin")); // 添加用户名claims.Add(new Claim(ClaimTypes.NameIdentifier, "1080")); // 添加用户 ID// 设置 Token 的过期时间DateTime expres = DateTime.Now.AddSeconds(jwtconfig.Value.Expres);Console.WriteLine($"过期时间{expres}");// 从配置文件中获取 JWT 密钥并转换为字节数组byte[] secbyse = Encoding.UTF8.GetBytes(jwtconfig.Value.Key);// 创建 SymmetricSecurityKey 对象并使用 HmacSha256 算法对密钥进行签名var secKey = new SymmetricSecurityKey(secbyse);var credetials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256);// 创建 JwtSecurityToken 对象并设置声明、过期时间和签名信息var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expres, signingCredentials: credetials);// 生成 JWT Token 字符串并返回string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);return jwt;}
6)再在program.cs文件中验证传入的token,代码如下:
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";//验证失败返回401context.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";//验证失败返回401context.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";//验证失败返回401context.Response.StatusCode = StatusCodes.Status200OK;context.Response.WriteAsync(result);return Task.FromResult(result);}context.Response.ContentType = "application/json";//验证失败返回401context.Response.StatusCode = StatusCodes.Status200OK;context.Response.WriteAsync(result);return Task.FromResult(result);}};});app.UseAuthentication();//.NETCore验证中间件,必须有。并且在 app.UseAuthorization();之前
7)、在需要权限的方法或控制器上加上特性[Authorize]
[HttpGet(Name = "GetAuthorize")][Authorize]public IEnumerable<WeatherForecast> Get(){//doing}


如果Token为空的效果:

注:在swagger加token需要另外在program.cs配置,代码如下:
builder.Services.AddSwaggerGen(s =>{//添加安全定义s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme{Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",Name = "Authorization",In = ParameterLocation.Header,Type = SecuritySchemeType.ApiKey,BearerFormat = "JWT",Scheme = "Bearer"});//添加安全要求s.AddSecurityRequirement(new OpenApiSecurityRequirement {{new OpenApiSecurityScheme{Reference =new OpenApiReference{Type = ReferenceType.SecurityScheme,Id ="Bearer"}},new string[]{ }}});});
添加好重启程序后会在swagger的右上方增加如下按钮,打开按钮根据提示即可完成添加。

结语
本文介绍了ASP.NET Core如使用JwtBearer,以及JwtBearer生成token验证的验证过程。希望对你有所收获,欢迎留言或吐槽。