验证 JWT 得到一个奇怪的“Unable to match key kid”错误

Validating JWT getting a strange “ Unable to match key kid” error

我正在尝试使用下面的代码验证有效的 JWT,但出现了一个奇怪的错误

"IDX10501: Signature validation failed. Unable to match key: 
kid: 'System.String'.
Exceptions caught:
 'System.Text.StringBuilder'. 
token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'."

这是我的验证方法

 ClaimsPrincipal principal = null;
         var token = "JWT GOES HERE"
            try
            {
                string sec = "000uVmTXj5EzRjlnqruWF78JQZMT";                    
                var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));

                var now = DateTime.UtcNow;
                SecurityToken securityToken;
               
                string tokenIssuer = "https://MyIssuer.com";             

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {                     
                    ValidIssuer = tokenIssuer,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,                        
                    IssuerSigningKey = securityKey
                };
                 JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                principal = handler.ValidateToken(token, validationParameters, out securityToken); <---Errors here
}

这是我的智威汤逊的价值。我使用的是正确的发行人

{
  "alg": "RS256",
  "kid": "dev",
  "x5t": "Sm7aAUSt4Fdv7X1b9jQDf8XwbvQ",
  "pi.atm": "xxe8"
}.{
  "scope": [],
  "client_id": "ClientABC",
  "iss": "https://MyIssuer.com",
  "jti": "1JLDz",
  "sub": "ClientABC",
  "exp": 1601609852
}.[Signature]

我在这里错过了什么?是 SymmetricSecurityKey 因为这个算法是 RS256?我的 TokenValidationParameter 中是否遗漏了什么?

更新 经过进一步调查,我得到了错误。

IDX10501: Signature validation failed. Unable to match key: 
kid: 'dev'.
Exceptions caught:
 'System.NotSupportedException: IDX10634: Unable to create the SignatureProvider.
Algorithm: 'RS256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey, KeyId: '', InternalId: 'TdfWgWjCVeM60F3C5TOogJuka1aR5FA_xchwhY9MHH4'.'
 is not supported. The list of supported algorithms is available here: https://aka.ms/IdentityModel/supported-algorithms
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures, Boolean cacheProvider)

尝试使用 SecurityAlgorithms.HmacSha256

发行令牌时的示例:

Users user = _context.Users.FirstOrDefault(c => c.UserName == userName && c.Password == password); 
            if(user == null)
            {
                return Unauthorized();
            }

            Claim[] claims = new Claim[]
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("Name", user.Name),
                new Claim("Email", user.Email),
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("000uVmTXj5EzRjlnqruWF78JQZMT"));

            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new
                JwtSecurityToken(
                                "MyProject",
                                "MyClient",
                                claims,
                                expires: DateTime.Now.AddMinutes(30),
                                signingCredentials: signingCredentials);

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

如果你使用的是.net core app,那么在Startup.cs中,在ConfigureServices方法中写入这段代码来验证令牌:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidAudience = "MyClient",
                        ValidIssuer = "MyProject",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("000uVmTXj5EzRjlnqruWF78JQZMT"))
                    };
                });

另外不要忘记将以下行添加到 Startup.cs

中的 Configure 方法中
app.UseAuthentication();
app.UseAuthorization();

问题是您正尝试将对称密钥与非对称算法结合使用。 RSA 算法需要 public 和私钥。

尝试使用对称算法,例如 HS256 (HMAC-SHA256)。