0
votes

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

enter image description here

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 enter image description here

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);
    }
1
When the token is updated in hwt.io in the moment when you paste the secret, then the secret is not the same that was used to sign the token. Are you sure that the backend uses the same secret for signing and verification?jps
Once on my application the server had removed the Authorization header from every request. Can you dump the request headers from any public function and see if header token is properly set.Hášíl Páůďýál
jps - I'm not sure I understand your question. I know the token changes when I add the secret key. BUt I'm not sure how to answer your question about signing and verification.user1186050
@user1186050: When you have the correct secret (the one that was used to sign the token) then you should see no change of the signature on jwt.io. What I mean in my question is, you got a token from a server and this token is signed. So the server used a certain secret to sign it. Later you make a request and get an error saying the signature is invalid. When you send the original token that you got from the server, there should be no problem. If there is a problem, the server maybe uses a different secret during verification.jps
Ok, so I do see the token change in JWT.io when I add the secret. Is that bad? But another concern I have is that in the video tutorial I'm following, the instructor doesn't add the secret at all and it is valid and he can pass it to the controller and have it authenticate properly. I'm just wondering if having different versions of Identity from what he's using might be an issue?user1186050

1 Answers

1
votes

I added

app.Authentication()

to startup and it worked...