提问者:小点点

验证JWT得到一个奇怪的“无法匹配关键孩子”的错误


我试图用下面的代码验证一个有效的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
}

这是我的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]

我在这里错过了什么?对称安全密钥是对称安全密钥,因为这个算法是RS256吗?我的令牌验证参数中是否缺少某些内容?

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

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)

共2个答案

匿名用户

尝试使用安全算法.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 核心应用,则在 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"))
                    };
                });

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

app.UseAuthentication();
app.UseAuthorization();

匿名用户

问题是您正在尝试使用具有非对称算法的对称密钥。RSA 算法需要公钥和私钥。

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