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
- We're using
JwtSecurityTokenHandlerto generate JWT tokens. - We define a
SecurityTokenDescriptorwhere we set the subject (claims), expiry time, and signing credentials. - In the
Expiresproperty ofSecurityTokenDescriptor, we set the expiry time to 10 years from the current time usingDateTime.UtcNow.AddYears(10). - Finally, we create and return the JWT token using
CreateTokenmethod ofJwtSecurityTokenHandler.
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.
Join the conversation! Your thoughts help the community grow.