JWT Token Expiry Timestamp in C#

By FoxLearn 1/10/2025 2:24:25 AM   101
To decode a JWT token and extract its expiration time (expiry), you can follow these steps in C#.

IdentityServer, along with other systems, uses JWT tokens to establish secure claims between IdentityServer and your application. These tokens are trusted because they are digitally signed using a private key. The term JWT stands for JSON Web Token, meaning when you say "JWT token," you're essentially saying "JSON Web Token token."

A JWT is composed of three parts, encoded in Base64 URL format: a header, a payload, and a signature.

To extract the expiration timestamp, you need to decode the payload section of the token.

Install the Required NuGet Package

First, install the following package:

Microsoft.IdentityModel

Create a Model Class for the Payload

The JWT token's payload contains the expiration time, which is stored as a Unix timestamp (exp).

public class JwtToken
{
    public long exp { get; set; }
}

Create a Method to Deserialize the Payload and Extract the Expiration Time

The JWT token consists of three parts: header, payload, and signature.

To extract the expiration timestamp, you need to decode the payload (the second part of the token) from Base64 URL format, then convert the exp field to a DateTime.

using Microsoft.IdentityModel.Tokens;
using System;
using System.Text.Json;

public class JwtDecoder
{
    public DateTime GetExpiryTimestamp(string accessToken)
    {
        try
        {
            // Ensure the token is not null or empty
            if (string.IsNullOrWhiteSpace(accessToken))
                return DateTime.MinValue;

            // Ensure the token has three parts (header, payload, signature)
            if (!accessToken.Contains("."))
                return DateTime.MinValue;

            // Split the token into its three parts
            string[] parts = accessToken.Split('.');

            // Decode the payload part (the second part)
            string decodedPayload = Base64UrlEncoder.Decode(parts[1]);

            // Deserialize the decoded payload to extract the 'exp' field
            JwtToken payload = JsonSerializer.Deserialize<JwtToken>(decodedPayload);

            // Convert the 'exp' field (Unix timestamp) to DateTime
            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(payload.exp);

            // Return the local DateTime equivalent
            return dateTimeOffset.LocalDateTime;
        }
        catch (Exception)
        {
            // If an error occurs (e.g., invalid token format), return a default DateTime value
            return DateTime.MinValue;
        }
    }
}

A JWT token consists of three parts: the header, the payload, and the signature, separated by periods (.).

  • Header: Contains information about the algorithm used to sign the token.
  • Payload: Contains claims and data, including the expiration time (exp).
  • Signature: Used to verify the token’s authenticity.

The payload is Base64 URL encoded. We use the Base64UrlEncoder.Decode() method to decode it. This gives us the raw JSON string, which we then deserialize into a JwtToken object.

The expiration time (exp) is stored as a Unix timestamp (seconds since January 1, 1970). We use DateTimeOffset.FromUnixTimeSeconds() to convert it into a DateTime object.

If the token is invalid or any other error occurs, the method will return DateTime.MinValue.

class Program
{
    static void Main(string[] args)
    {
        string jwtToken = "your-jwt-token-here";
        
        JwtDecoder decoder = new JwtDecoder();
        DateTime expiry = decoder.GetExpiryTimestamp(jwtToken);
        
        Console.WriteLine("Token Expiry: " + expiry);
    }
}

This will decode the JWT token, extract the expiry time, and print it out.