12

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;
    }
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
user584018
  • 10,186
  • 15
  • 74
  • 160
  • 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? – ProgrammingLlama Jan 27 '22 at 13:29
  • Please check the answer here: https://stackoverflow.com/questions/39926104/what-format-is-the-exp-expiration-time-claim-in-a-jwt – Luke Briner Jan 27 '22 at 13:32
  • @Llama, there is one property `ExpiresOn` coming as part of access token, how to compare this DateTimeOffset with current date? – user584018 Jan 27 '22 at 13:34
  • I'm not seeing `ExpiresOn` in `JwtSecurityToken`'s docs ([here](https://learn.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.jwt.jwtsecuritytoken?view=azure-dotnet)), though it does state that `ValidTo` represents the `exp` claim. Where are you seeing the `ExpiresOn` property? – ProgrammingLlama Jan 27 '22 at 13:37
  • 3
    Wait, are you just asking for something like `if (token.ExpiresOn > DateTimeOffset.UtcNow)` or something? – ProgrammingLlama Jan 27 '22 at 13:40
  • @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` token – user584018 Jan 27 '22 at 13:40
  • @Llama, I got my answer. `if (token.ExpiresOn > DateTimeOffset.UtcNow)`. Thanks! – user584018 Jan 27 '22 at 13:42
  • I guess [this answers your question then](https://stackoverflow.com/questions/36063651/comparing-two-datetimeoffsets). – ProgrammingLlama Jan 27 '22 at 13:44

3 Answers3

18

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;
    }
boletus151
  • 211
  • 2
  • 5
9

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;
}
Sinan ILYAS
  • 1,212
  • 1
  • 12
  • 10
  • This is still not valid for me on IIS Express Win 10 VS2019 .NET Core 5. I am on GMT+7 – toha May 16 '23 at 06:31
  • 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. – toha May 16 '23 at 09:12
  • I'm on GMT+3 but have no problems with this code. – Sinan ILYAS May 17 '23 at 07:16
1

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

RahulKumarShaw
  • 4,192
  • 2
  • 5
  • 11
  • 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! – user584018 Jan 31 '22 at 06:40