验证 JWT 时出现奇怪的“无法匹配关键孩子”错误

Cod*_*n03 8 c# claims-based-identity oauth-2.0 jwt owin

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

"IDX10501: Signature validation failed. Unable to match key: 
kid: 'System.String'.
Exceptions caught:
 'System.Text.StringBuilder'. 
token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'."
Run Code Online (Sandbox Code Playgroud)

这是我的验证方法

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

这是我的 JWT 的值。我使用的是正确的发行人

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

我在这里缺少什么?由于该算法是 RS256,所以是 SymmetricSecurityKey 吗?我的 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)
Run Code Online (Sandbox Code Playgroud)

ama*_*l50 3

尝试使用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));
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 .net core 应用程序,则在Startup.csConfigureServices方法中编写以下代码来验证令牌:

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

另外,不要忘记将以下行添加到Startup.cs中的配置方法中

app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)