AzureAD / azure-activedirectory-identitymodel-extensions-for-dotnet

IdentityModel extensions for .Net
MIT License
1.06k stars 401 forks source link

JwtSecurityTokenHandler.ReadJwtToken is not reading the issuer #3005

Open abhaysharma3021 opened 1 week ago

abhaysharma3021 commented 1 week ago

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 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);
}

token variable value:

{
    "alg": "HS256",
    "typ": "JWT"
}
{
    "nameid": "52bab80c-422c-4ac3-88bc-a960f55b7e59",
    "email": "abhay.sharma.3021@gmail.com",
    "unique_name": "Abhay Sharma",
    "role": "Admin",
    "nbf": 1731044568,
    "exp": 1731649365,
    "iat": 1731044568,
    "iss": "https://localhost:7039",
    "aud": "https://localhost:7039"
}

jwtToken variable value:

{
    "alg": "HS256"
}
{
    "nameid": "52bab80c-422c-4ac3-88bc-a960f55b7e59",
    "unique_name": "Abhay Sharma",
    "nbf": 1731044568,
    "iat": 1731044568,
    "aud": "https://localhost:7039"
}

When reading the same token, it does not show the iss. Due to this, when validating the token, I always get an error.