2

以下是我正在使用的 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 令牌已过期而失败。

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

有任何想法吗?谢谢!

4

2 回答 2

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
            }
        }
    };
})
于 2018-11-14T14:25:30.490 回答
1

使用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;
        }
    };
});
于 2019-10-07T07:09:04.653 回答