Alonso Contreras
Alonso Contreras

Reputation: 675

Invalid Signature for token generate in c# with JWT

i learned to generate tokens with ASP.Net core...

I've a method that generate a token validation... this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJQYXR5IiwianRpIjoiY2Q5OGE3NjMtOGRkZC00NWM1LTg3MzAtMGE2MDBjZDE1NTg1IiwiZXhwIjoxNTUwNzE2OTQwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjYzOTM5LyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NjM5MzkvIn0.ndvWn-pBwdo7UlxFvuE0IPWnxpDtzAKTfq_FRkgMFeM

And when y paste token in jwt.io, this show: Invalid Signature, but nevertheless the token has values user.... why jwt.io show this message ?

this method that generates token:

    public static string CreateToken(User user, string keyValue, string issuer)
    {
        /* keyValue = "veryVerySecretKey" */
        /* issuer = "http://localhost:63939/" */

        var claims = new[] {
          new Claim(JwtRegisteredClaimNames.Sub, user.Name),
          new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString())
        };



        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyValue));

        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(issuer,
          issuer,
          claims,
          expires: DateTime.Now.AddMinutes(30),
          signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

Upvotes: 7

Views: 9439

Answers (2)

Mawardy
Mawardy

Reputation: 3818

In my case it was that the security key was less than 128 bit , try to write a longer key.

Upvotes: 0

Sergio Cabral
Sergio Cabral

Reputation: 6968

When you use jwt.io and paste token into input always show "Invalid Signature".

It's not a error. You must be fill the field "your-256-bit-secret" with the value of your keyValue variable.

enter image description here

Upvotes: 17

Related Questions