I am using System.IdentityModel.Tokens.Jwt package and the below code decoding the jwt token, but it won't give exp value?
var handler = new JwtSecurityTokenHandler();
var decodedValue = handler.ReadJwtToken("token");
How to get exp and compare it with the current DateTime to calculate token is expired or not?

Update:
I am using Azure.Core.AccessToken where I have the below property,
public DateTimeOffset ExpiresOn
{
get;
}
I use this:
using System.IdentityModel.Tokens.Jwt;
public static long GetTokenExpirationTime(string token)
{
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);
var tokenExp = jwtSecurityToken.Claims.First(claim => claim.Type.Equals("exp")).Value;
var ticks= long.Parse(tokenExp);
return ticks;
}
public static bool CheckTokenIsValid(string token)
{
var tokenTicks = GetTokenExpirationTime(token);
var tokenDate = DateTimeOffset.FromUnixTimeSeconds(tokenTicks).UtcDateTime;
var now = DateTime.Now.ToUniversalTime();
var valid = tokenDate >= now;
return valid;
}
This is how I check if a token is valid.
using System.IdentityModel.Tokens.Jwt;
private bool IsValid(string token)
{
JwtSecurityToken jwtSecurityToken;
try
{
jwtSecurityToken = new JwtSecurityToken(token);
}
catch (Exception)
{
return false;
}
return jwtSecurityToken.ValidTo > DateTime.UtcNow;
}
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