Vivek Nuna
Vivek Nuna

Reputation: 1

JWT token expiration not working in Asp.Net Core API?

I have set the token expiry to 1 minute, but I am not getting the 401 unauthorized error after 1 minute.

Startup.cs

.AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Configuration["Jwt:Issuer"],
                        ValidAudience = Configuration["Jwt:Issuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                    };
                });

Token Generation method:

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
int expiryMins = 1
var token = new JwtSecurityToken(_configuration["Jwt:Issuer"],
  _configuration["Jwt:Issuer"],
  null,
  expires: DateTime.UtcNow.AddMinutes(expiryMins),
  signingCredentials: credentials);

return new JwtSecurityTokenHandler().WriteToken(token);

Upvotes: 5

Views: 6016

Answers (1)

juunas
juunas

Reputation: 58873

As we discussed in the comments, this was due to the clock skew setting defaulting to 5 minutes, allowing tokens to be considered valid max 5 minutes after expiry (from the server's point of view that validates the token). Clock skew setting exists because the server that issues the token and the server that validates the token might have slight differences in their clocks. Usually it is a good idea to have some flexibility here and the default of 5 minutes is okay. If you do not wish to have this behaviour, you can set ClockSkew on the TokenValidationParameters to 0 seconds.

Upvotes: 13

Related Questions