打击是我正在使用的JWT身份验证:
.AddJwtBearer(options =>
{
// options.SaveToken = false;
// options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(AuthConfig.GetSecretKey(Configuration)),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
options.Events = new JwtBearerEvents()
{
OnChallenge = c =>
{
c.HandleResponse();
// TODO: How to know if the token was expired?
return AspNetUtils.WriteJsonAsync(c.Response, new Result<string> { Message = "Unauthenticated.", IsError = true }
, 401);
},
};
})
身份验证正常。对于新要求,我需要知道是否由于JWT令牌过期而导致身份验证失败。
请注意,身份验证失败可能有多种原因。令牌可能会丢失,被篡改或过期。
有什么想法吗?谢谢!
答案 0 :(得分:2)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = context =>
{
if(context.Exception is SecurityTokenExpiredException)
{
// if you end up here, you know that the token is expired
}
}
};
})
答案 1 :(得分:0)
使用OnChallenge属性:
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnChallenge = context =>
{
if (context?.AuthenticateFailure is SecurityTokenExpiredException)
{
var error = context.Error; // "invalid_token"
var errorDescription = context.ErrorDescription; // "The token is expired"
}
return Task.CompletedTask;
}
};
});