I'm using ASP.NET Core 8 Web API, and I encountered an "Unauthorized" error with the token I generated. While debugging, I discovered that JwtSecurityTokenHandler.ReadJwtToken is not reading the iss claim from the token. However, when I checked the same token on the jwt.io website, I could see the iss claim present. I'm confused about what's happening. Below, I'm attaching a sample of the code for reference.
This is the GenerateToken function, where I'm writing the token and reading it immediately to debug what the issue is.
private string GenerateToken(User user)
{
var jwtSettings = _configuration.GetSection("Jwt");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["key"]!));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var issuer = jwtSettings["Issuer"]!;
var audience = jwtSettings["Audience"]!;
// Define token claims
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Email, user.Email.ToString()),
new Claim(ClaimTypes.Name, $"{user.Name}")
};
foreach(var roles in user.UserRoles)
{
claims.Add(new Claim(ClaimTypes.Role, roles.Role.Name));
}
// SecurityTokenDescriptor for generating the token
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddDays(double.Parse(jwtSettings["ExpiresInDays"]!)),
Issuer = issuer.Trim(),
Audience = audience.Trim(),
SigningCredentials = credentials
};
var tokenHandler = new JwtSecurityTokenHandler();
// Create and write token
var token = tokenHandler.CreateToken(tokenDescriptor);
var writtenToken = tokenHandler.WriteToken(token);
// Read back the token
var jwtToken = tokenHandler.ReadJwtToken(writtenToken);
return tokenHandler.WriteToken(token);
}
Hi,
I'm using ASP.NET Core 8 Web API, and I encountered an "Unauthorized" error with the token I generated. While debugging, I discovered that
JwtSecurityTokenHandler.ReadJwtToken
is not reading theiss
claim from the token. However, when I checked the same token on the jwt.io website, I could see theiss
claim present. I'm confused about what's happening. Below, I'm attaching a sample of the code for reference.This is the
GenerateToken
function, where I'm writing the token and reading it immediately to debug what the issue is.token variable value:
jwtToken variable value:
When reading the same token, it does not show the
iss
. Due to this, when validating the token, I always get an error.