How to Set Long Expiry to JWT Token?

To set a long expiry time for a JSON Web Token (JWT) in C#, you need to configure the token's expiration claim accordingly. Here's how you can do it.

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

public class JwtService
{
    private readonly string _secretKey;

    public JwtService(string secretKey)
    {
        _secretKey = secretKey;
    }

    public string GenerateJwtToken(string username)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Convert.FromBase64String(_secretKey);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, username)
            }),
            Expires = DateTime.UtcNow.AddYears(10), // Set expiry time to 10 years from now
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
}

In this code

  1. We're using JwtSecurityTokenHandler to generate JWT tokens.
  2. We define a SecurityTokenDescriptor where we set the subject (claims), expiry time, and signing credentials.
  3. In the Expires property of SecurityTokenDescriptor, we set the expiry time to 10 years from the current time using DateTime.UtcNow.AddYears(10).
  4. Finally, we create and return the JWT token using CreateToken method of JwtSecurityTokenHandler.

Make sure to replace _secretKey with your actual secret key. Additionally, ensure that you handle the secret key securely, as it's used to sign and verify the JWT tokens.


Recommended Free Ebook
Similar Articles