NET5+JWT+VUE+Swagger登录权限验证3——JWT权限认证1
注册:
//配置认证服务
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
//是否验证发行人
ValidateIssuer = true,
ValidIssuer = Configuration.GetSection("Jwt:issuer").Value,//发行人
//是否验证受众人
ValidateAudience = true,
ValidAudience = Configuration.GetSection("Jwt:audience").Value,//受众人
//是否验证密钥
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("Jwt:secret").Value)),
ValidateLifetime = true, //验证生命周期
RequireExpirationTime = true, //过期时间
ClockSkew = TimeSpan.Zero,
};
o.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
//令牌已过期
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
//向消息头添加过期标识
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
2、启用
app.UseRouting();
//使用已注册跨域服务
app.UseCors("any");
//1.先开启认证
app.UseAuthentication();
//2.再开启授权
app.UseAuthorization();
3、配置文件
"Jwt": {
"secret": "123456789qwertyuiop",//密匙
"issuer": "SWCS",//发行人
"audience": "Api",//订阅人
"accessTokenExpiration": 1,
"refreshTokenExpiration": 30
},