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

时间:2018-11-13 22:24:28

标签: asp.net-core jwt asp.net-core-2.1 jwt-auth

打击是我正在使用的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令牌过期而导致身份验证失败。

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

有什么想法吗?谢谢!

2 个答案:

答案 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;
        }
    };
});