Asp.Net 核心和 JWT 身份验证:如何知道身份验证失败是因为令牌过期?

Asp.Net Core & JWT authentication: How to know authentication failed because token expired?

下面是我使用的 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 令牌已过期。

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

有什么想法吗?谢谢!

.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
            }
        }
    };
})

使用 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;
        }
    };
});