Not sure why my token is invalid. I fetch it with Postman calling login() and then pasting it into JWT.io it says "invalid signature" I can paste my secret key into JWT.io and it will validate, but that doesn't seem right because it then changes the token to something different then what my login method returns to the user! Here is my token and the secret key is "Super secret key". The token becaomes valid when pasted in JWT.io
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIxIiwidW5pcXVlX25hbWUiOiJjaHVjayIsInJvbGUiOlsiTWVtYmVyIiwiQWRtaW4iXSwibmJmIjoxNTc5MTU5NDQ0LCJleHAiOjE1NzkyNDU4NDQsImlhdCI6MTU3OTE1OTQ0NH0.Uau2W66y7Kdj01MQbBeoOXiwVzQJSDMEZnbQc2jt1qUyfdc9N5bsla1VGMPHQPjRAcnKSfY3NwQBhCRE-SHZCQ
Here is where I paste my secret key to validate the token
Then I create a new Postman get query to fetch some values and I use the token sent back from the login. But I get 401 Unauthorized.
I added the token (same one that the login sent me not the changed one after I validated it) in postman like this
I also added "IdentityModelEventSource.ShowPII = true;" to the startup file to show additional debugging and here' what I see in the debug console.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler1 Failed to validate the token. Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey , KeyId: '. Exceptions caught: ''. token: '{"alg":"HS512","typ":"JWT"}.{"nameid":"1","unique_name":"chuck","role":["Member","Admin"],"nbf":1579159444,"exp":1579245844,"iat":1579159444}'.
I can paste my token generation code if asked. Any explanation in understanding what's going on here would be much appreciated. Questions - did I miss a step? Do I provide the same token the login sends me back to the authorized controller method or the changed token (tried both)?
Here is the code I use to create the token.
private async Task<string> GenerateJwtToken(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName)
};
var roles = await _userManager.GetRolesAsync(user);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var key = new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}