.net core中JWT授权、鉴权以及Swagger配置的使用
首先需要引入NuGet包=>System.IdentityModel.Tokens.Jwt
JWT授权:新建一个控制器,用于获取Token值
//登录成功 var claims = new Claim[] { new Claim(ClaimTypes.Name,writer.WriteName), new Claim("ID",writer.ID.ToString()), new Claim("UserName",writer.WriteLoginName), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF")); //issuer代表颁发Token的Web应用程序,audience是Token的受理者 var token = new JwtSecurityToken( issuer: "http://localhost:6060", audience: "http://localhost:5000", claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(5),//token有效时间 signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) ); var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
登录成功后,返回生成的token码,用于角色信息验证
JWT鉴权:同样需要引入相关NuGet包=>Microsoft.AspNetCore.Authentication.JwtBearer(注意版本,需要适配自己选择的框架,避免产生不必要的错误)
首先添加鉴权UseAuthorization() (鉴权和授权的顺序一定不能错,否则会报401的错误)

鉴权端同样需要写入JWT相关配置项,为避免代码拥挤,看着不直观,新起一个方法最后再加入到Service中
public static IServiceCollection AddCustomJWT(this IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF")), ValidateIssuer = true, ValidIssuer = "http://localhost:6060", ValidateAudience = true, ValidAudience = "http://localhost:5000", ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(0)//令牌失效时间 }; }); return services; }

在需要身份验证的控制器上加上Authorize特性即可

如果使用的Swagger,则需要另外设置引用相关组件,在SwaggerUI上才会出现填写Token码的地方。
services.AddSwaggerGen(c => { c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Description = "直接在下框中输入Bearer {token}(注意两者之间是一个空格)", Name = "Authorization", BearerFormat = "JWT", Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference=new OpenApiReference { Type=ReferenceType.SecurityScheme, Id="Bearer" } }, new string[] {} } }); });

浙公网安备 33010602011771号