I need to check if my JwtSecurityToken
is expired or not.
I'm using System.IdentityModel.Tokens.Jwt
library.
When a create a JwtSecurityToken
like this:
var token = new JwtSecurityToken(
issuer: token_issuer,
audience: token_audience,
claims: claims,
expires: DateTime.Now.AddMinutes(15),
signingCredentials: creds
);
And check its lifetime, I'm getting 2 hours after the current time.
I check the lifetime this way (only for test purposes):
var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;
And my method for validation:
private static bool ValidateToken(string token)
{
try
{
TokenValidationParameters validationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(token_salt),
ValidAudience = token_audience,
ValidIssuer = token_issuer,
RequireExpirationTime = true
};
var lifeTime = new JwtSecurityTokenHandler().ReadToken(token).ValidTo;
ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);
return true;
}
catch(Exception ex)
{
}
return false;
}
Can anyone explain what's happening or am I doing some wrong?
EDIT (for explanation purposes)
expiration = DateTime.Now.AddSeconds(5);
expiration = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc).AddSeconds(5);
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: '12/11/2017 10:16:12'
Current time: '12/11/2017 12:18:40'.
expiration = DateTime.UtcNow.AddSeconds(5);
But WHY the validation passes if when I run the validation was 13:12 and token's lifetime is 13:07? Is there a minimum time to bet set in expiration?
When ACCESS_TOKEN expires you need to call another api with REFRESH_TOKEN to get new ACCESS_TOKEN. The client application can get a new access token as long as the refresh token is valid and unexpired.
The JWT access token is only valid for a finite period of time. Using an expired JWT will cause operations to fail. As you saw above, we are told how long a token is valid through expires_in . This value is normally 1200 seconds or 20 minutes.
A JWT token that never expires is dangerous if the token is stolen then someone can always access the user's data. Quoted from JWT RFC: The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
I know, that this is an old question, but TokenValidationParameters
class has property called ClockSkew
, which is set by default to 5 minutes. It might be your problem, as it was mine. Just set this property to for example to 1 second - ClockSkew = TimeSpan.FromSeconds(1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With