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

Viewed 2070

Below is the JWT authentication I am using:

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

The authentication is working fine. For new requirements, I need to know if authentication failed because the JWT token was expired or not.

Note that authentication failed because of multi reasons. The token can be missing, tampered, or expired.

Any ideas? Thanks!

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

Using OnChallenge property:

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