I’m using JwtSecurityTokenHandler from the (Microsoft.IdentityModel.JsonWebTokens version 7.6.0) library for authentication in my API.
I’m unable to retrieve the same information from my token upon reading it as when it was written. Some information is missing in the payload, although the information that is present is correct.
I can successfully create the token with the desired information via CreateToken(tokenDescriptor). I can also convert it to a string using the WriteToken(token) method, and it still contains the information (verified with jwt.io). However, when I try to extract the information with ReadToken or ReadJwtToken, some information in the payload is missing, including the expiration date, which is blocking the token validation.
Here is my code:
public string GenerateToken(string userId, string databaseId)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_secretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, userId),
new Claim("databaseId", databaseId)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
// These are Tests
Console.WriteLine(token); // returns {"alg":"HS256","typ":"JWT"}.{"unique_name":"13","databaseId":"2","nbf":1717747146,"exp":1718351946,"iat":1717747146}
var tokenString = tokenHandler.WriteToken(token);
Console.WriteLine(tokenString); // returns eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEzIiwiZGF0YWJhc2VJZCI6IjIiLCJuYmYiOjE3MTc3NDcxNDYsImV4cCI6MTcxODM1MTk0NiwiaWF0IjoxNzE3NzQ3MTQ2fQ.4ZRS5RYXzir5mwz8yXlu97y3H29BeJFtC3-3RQ8p0vw
SecurityToken newToken = tokenHandler.ReadJwtToken(tokenString);
Console.WriteLine(newToken); // returns {"alg":"HS256"}.{"unique_name":"13","nbf":1717747146,"iat":1717747146}
return tokenHandler.WriteToken(token);
}
user25464035 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1