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

3

13

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;
    }
Alexander answered 27/1, 2022 at 13:28 Comment(8)
Do you mean that for the token in question, the ValidTo field isn't returning a valid DateTime representative of the expiry? If not, can you clarify your question, please?Cloraclorinda
Please check the answer here: #39926604Norty
@Llama, there is one property ExpiresOn coming as part of access token, how to compare this DateTimeOffset with current date?Alexander
I'm not seeing ExpiresOn in JwtSecurityToken's docs (here), though it does state that ValidTo represents the exp claim. Where are you seeing the ExpiresOn property?Cloraclorinda
Wait, are you just asking for something like if (token.ExpiresOn > DateTimeOffset.UtcNow) or something?Cloraclorinda
@Llama, I have azure ad token which generates through azure managed identity and looks like it's different than jwt token. it's a Azure.Core.AccessToken tokenAlexander
@Llama, I got my answer. if (token.ExpiresOn > DateTimeOffset.UtcNow). Thanks!Alexander
I guess this answers your question then.Cloraclorinda
H
21

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;
}
Heroic answered 6/12, 2022 at 6:27 Comment(3)
This is still not valid for me on IIS Express Win 10 VS2019 .NET Core 5. I am on GMT+7Pattison
Oh, maybe this is correct too. because, at my localhost, this code is working fine. But when at development server, the release process maybe not working. I will re-check at another project. I will try to use this and another one use first answer.Pattison
I'm on GMT+3 but have no problems with this code.Heroic
L
24

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;
    }
Lair answered 29/8, 2022 at 15:20 Comment(4)
System.Linq is required to use the First method of the Claims IEnumerator. Add using System.Linq; at the top.Enate
Why not use var now = DateTime.UtcNow; instead of var now = DateTime.Now.ToUniversalTime(); ?Scanties
I was just testing other ways...Lair
This is correct way for me..Pattison
H
21

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;
}
Heroic answered 6/12, 2022 at 6:27 Comment(3)
This is still not valid for me on IIS Express Win 10 VS2019 .NET Core 5. I am on GMT+7Pattison
Oh, maybe this is correct too. because, at my localhost, this code is working fine. But when at development server, the release process maybe not working. I will re-check at another project. I will try to use this and another one use first answer.Pattison
I'm on GMT+3 but have no problems with this code.Heroic
B
2

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

Boer answered 28/1, 2022 at 9:13 Comment(1)
hello @RahulKumarShaw-MT... my question mainly around, how to decode the jwt token and get the exp value out of it in C#, 2nd part is compare where you're solution works for me. But I got answer like this if (token.ExpiresOn > DateTimeOffset.UtcNow). Thanks for your answer and appreciate!Alexander

© 2022 - 2024 — McMap. All rights reserved.