user584018
user584018

Reputation: 11304

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;
    }

Upvotes: 16

Views: 37692

Answers (4)

Reza Taba
Reza Taba

Reputation: 1904

If needing DateTime

using System.IdentityModel.Tokens.Jwt;

public static DateTime? GetTokenExpirationDate(string token)
{
    var handler = new JwtSecurityTokenHandler();

    if (!handler.CanReadToken(token))
        return null;

    var jwtToken = handler.ReadJwtToken(token);
    var expClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "exp");

    if (expClaim == null) return null;

    // Convert the expiration from Unix epoch to DateTime
    var expSeconds = long.Parse(expClaim.Value);
    return DateTimeOffset.FromUnixTimeSeconds(expSeconds).UtcDateTime;
}

Usage:
string token = "your_access_token_here";
DateTime? expiration = GetTokenExpirationDate(token);

if (expiration.HasValue)
{
    Console.WriteLine($"Token expires at: {expiration.Value}");
}
else
{
    Console.WriteLine("Invalid token or no expiration claim.");
}

Upvotes: 0

Sinan ILYAS
Sinan ILYAS

Reputation: 1373

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;
}

Upvotes: 24

boletus151
boletus151

Reputation: 300

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;
    }

Upvotes: 26

RahulKumarShaw
RahulKumarShaw

Reputation: 4602

Glad that you found your solution Posting the complete answer for helping community member when they will encounter the same problem.

For Reproducing the issue, I have generated an Access token using Ouath2.0 with client credential with shared secret.

enter image description here

C# Code for converting Unix timestamps into DateTimes

using System;

public class HelloWorld
{
    
    public static DateTime ConvertFromUnixTimestamp(int timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp); //
}
    
    public static void Main(string[] args)
    {
        Console.WriteLine ("Hello Mono World");
        int timestamp=1643438945;
        DateTime date=ConvertFromUnixTimestamp(timestamp);
        Console.WriteLine("Token Expire time "+date);
        if (date>DateTimeOffset.UtcNow)
        {
            Console.WriteLine ("Token is not expire");
        }
        else {
            Console.WriteLine ("Token has expired");
        }
    }
}

Output--

enter image description here

Upvotes: 4

Related Questions