简体   繁体   中英

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

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.

在此处输入图片说明

就我而言,安全密钥小于 128 位,请尝试编写更长的密钥。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM