Asp.Net Core和JWT身份验证:如何知道身份验证因令牌过期而失败?

Loc*_*Loc 1 jwt asp.net-core jwt-auth asp.net-core-2.1

以下是我正在使用的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);
        },
    };
});
Run Code Online (Sandbox Code Playgroud)

身份验证正常。对于新要求,我需要知道是否由于JWT令牌过期而导致身份验证失败。

请注意,身份验证失败可能有多种原因。令牌可能丢失,被篡改或过期。

有任何想法吗?谢谢!

Wim*_*ets 5

.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
            }
        }
    };
})
Run Code Online (Sandbox Code Playgroud)