使用 JWT 在 C# 中生成令牌的签名无效

Alo*_*ras 7 c# authentication token jwt

我学会了用 ASP.Net core 生成令牌...

我有一个生成令牌验证的方法......这个

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJQYXR5IiwianRpIjoiY2Q5OGE3NjMtOGRkZC00NWM1LTg3MzAtMGE2MDBjZDE1NTg1IiwiZXhwIjoxNTUwNzE2OTQwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjYzOTM5LyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NjM5MzkvIn0.ndvWn-pBwdo7UlxFvuE0IPWnxpDtzAKTfq_FRkgMFeM
Run Code Online (Sandbox Code Playgroud)

当您将令牌粘贴到 jwt.io 中时,这会显示:无效签名,但令牌仍然具有值 user....为什么 jwt.io 显示此消息?

生成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);
    }
Run Code Online (Sandbox Code Playgroud)

Ser*_*ral 16

当您使用 jwt.io 并将令牌粘贴到输入中时,始终显示“无效签名”。

这不是一个错误。您必须使用变量的值填写“your-256-bit-secret”字段keyValue

在此输入图像描述