'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?
Update:
I am using Azure.Core.AccessToken where I have the below property,
public DateTimeOffset ExpiresOn
{
get;
}
Solution 1:[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.
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--
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RahulKumarShaw-MT |



