oauth-2.0 - IDX10501 : Signature validation failed. 无法匹配 key

标签 oauth-2.0 jwt azure-active-directory openid-connect adfs

我的任务是使用来自外部应用程序的 ADFS token 对 API 进行身份验证,因此我创建了两个应用程序,一个是 MVC 应用程序,可以说 它使用 SSO 凭据进行身份验证,另一个是 WEB API 应用程序,可以说 ,所以在这里从 A,我正在使用 A 的 ADFS token 调用 B 的 API,但是,我收到错误消息。有没有人帮我解决这个问题?

以下是应用程序中 WEB API 中的代码

           ConfigurationManager<OpenIdConnectConfiguration> configManager =
                new ConfigurationManager<OpenIdConnectConfiguration>(openIdConfig, new 
                                                                     OpenIdConnectConfigurationRetriever());

            OpenIdConnectConfiguration config = 
            configManager.GetConfigurationAsync().GetAwaiter().GetResult();
            result.EmailId = Claims.FirstOrDefault(claim => claim.Type == "upn").Value;
            result.WindowsNTId = Claims.FirstOrDefault(claim => claim.Type == "unique_name").Value;
            var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            result.TokenCreatedOn = utc0.AddSeconds(Convert.ToInt64((Claims.FirstOrDefault(claim => 
            claim.Type == "iat").Value)));
            result.TokenExpiresOn = utc0.AddSeconds(Convert.ToInt64((Claims.FirstOrDefault(claim => 
            claim.Type == "exp").Value)));

            // Use System.IdentityModel.Tokens.Jwt library to validate the token
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                ValidateIssuer = true,
                ValidIssuer = config.Issuer,
                IssuerSigningKeys = config.SigningKeys,
                ValidateAudience = true,
                ValidAudience = expectedAudience
            };

            SecurityToken validatedToken;

            try
            {
                var claimsPrincipal = tokenHandler.ValidateToken(RawData, tokenValidationParameters, 
                out validatedToken);

            }
            catch (Exception ex)
            {

            }

下面是异常消息。
    IDX10501: Signature validation failed. Unable to match key: 
    kid: 'System.String'.
    Exceptions caught:System.Text.StringBuilder'. 
    token: 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken'.  

最佳答案

当解码的 key (kid) 不是有效 key (可能是旧 key ,因为证书 key 通常会更改)时,就会发生这种情况。
来自 https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/dev/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs

if (kidExists)
{
     if (kidMatched)
     throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSignatureException(LogHelper.FormatInvariant(TokenLogMessages.IDX10511, keysAttempted, jwtToken.Kid, exceptionStrings, jwtToken)));

     throw LogHelper.LogExceptionMessage(new SecurityTokenSignatureKeyNotFoundException(LogHelper.FormatInvariant(TokenLogMessages.IDX10501, jwtToken.Kid, exceptionStrings, jwtToken)));
}
就我而言,问题的原因是 key 模数中存在空的第一个字节。解决方案是删除第一个空字节。
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1122
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(configFileUrl, new OpenIdConnectConfigurationRetriever());
var openIdConfig = configManager.GetConfigurationAsync().Result; #region workaround for "Error validating identity token : IDX10511"
//The issue you are facing is caused by the null first byte.
//This is contrary to the JWA (https://tools.ietf.org/html/rfc7518#section-6.3.1.1).
//.NET Core will account for the null byte and .NET framework, apparently, won't.
List<SecurityKey> keys = new List<SecurityKey>();
foreach (var key in openIdConfig.SigningKeys)
{
     if (key.CryptoProviderFactory.IsSupportedAlgorithm("SHA256"))
     {
          var modulus = ((RsaSecurityKey)key).Parameters.Modulus;
          var exponent = ((RsaSecurityKey)key).Parameters.Exponent;

          if (modulus.Length == 257 && modulus[0] == 0)
          {
               var newModulus = new byte[256];
               Array.Copy(modulus, 1, newModulus, 0, 256);
               modulus = newModulus;
          }
          RSAParameters rsaParams = new RSAParameters();
          rsaParams.Modulus = modulus;
          rsaParams.Exponent = exponent;

          keys.Add(new RsaSecurityKey(rsaParams));
     }
     else
     {
          keys.Add(key);
     }
}
#endregion

TokenValidationParameters validationParameters =
new TokenValidationParameters
{
     // Validate the JWT Issuer (iss) claim
     ValidateIssuer = true,
     ValidIssuer = issuer,

     //// Validate the JWT Audience (aud) claim
     ValidateAudience = true,
     ValidAudience = audience,

     ValidateIssuerSigningKey = true,
     IssuerSigningKeys = keys,

     RequireExpirationTime = true,
     ValidateLifetime = true,
     RequireSignedTokens = true,
};

// Now validate the token. If the token is not valid for any reason, an exception will be thrown by the method
SecurityToken validatedToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

var claimsPrincipal = handler.ValidateToken(idToken, validationParameters, out validatedToken);

关于oauth-2.0 - IDX10501 : Signature validation failed. 无法匹配 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61006792/

相关文章:

node.js - 收到访问 token 后,无法在 Nodejs 中向 Google OAuth 2 发出经过身份验证的请求

PowerShell NuGet - "no match was found for the specified search criteria"、 "unable to find dependent packages"等

rest - 在 Laravel 中将 JWT Token 保存在何处

reactjs - 如何检索企业连接的可选声明(azure应用程序)

oauth - OAuth 1 的 future 是什么?

laravel - 自定义 token 响应 Laravel Passport

oauth-2.0 - 使用代码获取刷新 token 时出现内​​部故障?

java - JWT 解密,但抛出 mac check failed 错误

java - azure : Change Single Tenant Authentication to Multi Tenant using Java

azure - 如何使用应用程序注册和 azure cli 命令获取所有 azure 应用程序注册并查看 secret 的到期日期?