I’m working on JWT token generation and validation in .NET Core. Here is the code I use to generate my token:
string GenerateToken()
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(mySecret));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new Claim[] {
new(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
};
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddSeconds(10),
SigningCredentials = credentials,
Audience = "audience",
Issuer = "issuer"
};
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
return token;
}
And here is the code to validate a token:
void ValidateToken(string token)
{
JwtSecurityTokenHandler validationHandler = new();
var claimsPrincipal = validationHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(mySecret)),
ClockSkew = TimeSpan.Zero
}, out SecurityToken securityToken);
}
When the token has expired, I receive the following exception message:
IDX10223: Lifetime validation failed. The token is expired. ValidTo
(UTC): ‘6/9/2024 6:21:36 AM’, Current time (UTC): ‘6/9/2024 6:21:38
AM’.
This code sample is from a console application, but I’ve also tested it in a Web API, and it throws the same exception and returns a 401 status code.
I am using the Microsoft.AspNetCore.Authentication.JwtBearer package.
My question is: Why is this exception being thrown, and how can I handle expired tokens more gracefully without exceptions?
Any help or suggestions would be greatly appreciated.