3

In token's validation, I checked the token's lifetime and it was 13:07:10. When I run the validation it was 13:12 and the validation was successful. Why?

When it was about 13:15 I run the validation again and it threw an exception, as expected.

Is there a minimum expiration time for the token?


Creating the token:

var token = new JwtSecurityToken(
    issuer: token_issuer,
    audience: token_audience,
    claims: claims,
    expires: DateTime.Now.AddSeconds(5),                
    signingCredentials: creds
);

Validating the token:

private static bool ValidateToken(string token)
{
    try
    {
        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = new SymmetricSecurityKey(token_salt),
            ValidAudience = token_audience,
            ValidIssuer = token_issuer,
            RequireExpirationTime = true
        };

        ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);

        return true;
    }
    catch(SecurityTokenExpiredException ex)
    {

    }

    return false;
}
gregoryp
  • 920
  • 4
  • 15
  • 35

1 Answers1

6

This is due to the ClockSkew token validation parameter, which allows one to provide a buffer to account for clock discrepancies between the server issuing the JWT and the one validating it.

In .NET Core / 5+, you can change its value in the TokenValidationParameters object in the JwtBearer configuration in Startup as seen below. Its default is 300 seconds, or 5 minutes.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://some-jwt-token-issuer.com";
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                // Set the below to eliminate the skew
                ClockSkew = TimeSpan.Zero 
            };
        });
J.D. Mallen
  • 4,339
  • 3
  • 22
  • 33
Cawboy
  • 123
  • 2
  • 8