Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "exp" from jwt token and compare with it current time to check if token is expired

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?

enter image description here

Update:

I am using Azure.Core.AccessToken where I have the below property,

public DateTimeOffset ExpiresOn
    {
        get;
    }
like image 465
user584018 Avatar asked Dec 09 '25 21:12

user584018


2 Answers

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;
    }
like image 148
boletus151 Avatar answered Dec 12 '25 10:12

boletus151


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;
}
like image 45
Sinan ILYAS Avatar answered Dec 12 '25 09:12

Sinan ILYAS