services.AddAuthorization();
services.AddAuthentication(options =>
{
options.DefaultScheme = "bearer";
}).AddJwtBearer("bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = HelperLib.securityKey,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
context.Response.StatusCode = 408; // request timeout
}else if(context.Exception.GetType() == typeof(SecurityTokenSignatureKeyNotFoundException))
{
context.Response.StatusCode = 401; // security token signature is invalid
}else if(context.Response.GetType() == typeof(SecurityTokenInvalidSignatureException)){
context.Response.StatusCode = 408;
}
// if no token is set
context.Response.StatusCode = 402; // check if bearer has token
Console.WriteLine($"no token has been set {context.Response.StatusCode = 408}");
return Task.FromResult(0);
}
};
当用户使用jwt请求时,我正在尝试添加jwt身份验证, 也是为此,我想在用户会话过期时拒绝请求,并且没有令牌,它应该返回401,但就目前而言,即使没有令牌,用户仍可以请求发生什么事情,我有什么办法可以做到这一点?策略更好吗? ?