简体   繁体   English

OAuth Bearer令牌认证未通过签名验证

[英]OAuth Bearer token Authentication is not passing signature validation

I get the following error on the token consumer. 我在令牌使用者上收到以下错误。 Any help resolving this will be most appreciated. 解决该问题的任何帮助将不胜感激。 Thanks. 谢谢。


"IDX10503: Signature validation failed. “ IDX10503:签名验证失败。

Keys tried: 'System.IdentityModel.Tokens.SymmetricSecurityKey '. 尝试使用的密钥:“ System.IdentityModel.Tokens.SymmetricSecurityKey”。 Exceptions caught: 'System.InvalidOperationException: IDX10636: SignatureProviderFactory.CreateForVerifying returned null for key: 'System.IdentityModel.Tokens.SymmetricSecurityKey', signatureAlgorithm: ' http://www.w3.org/2001/04/xmldsig-more#hmac-sha256 '. 捕获的异常:'System.InvalidOperationException:IDX10636:SignatureProviderFactory.CreateForVerifying返回密钥的空值:'System.IdentityModel.Tokens.SymmetricSecurityKey',signatureAlgorithm:' http : //www.w3.org/2001/04/xmldsig-more#hmac -sha256 '。 at Microsoft.IdentityModel.Logging.LogHelper.Throw(String message, Type exceptionType, EventLevel logLevel, Exception innerException) at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm) at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters) '. 在Microsoft.IdentityModel.Logging.LogHelper.Throw(字符串消息,类型exceptionType,EventLevel logLevel,Exception innerException),在System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(字节[]编码的字节,字节[]签名,SecurityKey密钥,字符串算法)在System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(String token,TokenValidationParametersvalidationParameters)中。 token: 'token info was here'" 令牌:“令牌信息在这里”

Token Generation Code on OAuth server OAuth服务器上的令牌生成代码

 using (var ctlr = new EntityController())
        {
            var authRepo = ctlr.GetAuthModelRepository();

            string clientId;

            ticket.Properties.Dictionary.TryGetValue(WebConstants.OwinContextProps.OAuthClientIdPropertyKey, out clientId);

            if (string.IsNullOrWhiteSpace(clientId))
            {
                throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
            }


            //audience record
            var client = authRepo.FindAuthClientByOAuthClientID(clientId);

            var issued = ticket.Properties.IssuedUtc;
            var expires = ticket.Properties.ExpiresUtc;


            var hmac = new HMACSHA256(Convert.FromBase64String(client.Secret));
            var signingCredentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(hmac.Key),
                Algorithms.HmacSha256Signature, Algorithms.Sha256Digest);

            TokenValidationParameters validationParams =
                new TokenValidationParameters()
                {
                    ValidAudience = clientId,
                    ValidIssuer = _issuer,
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    RequireSignedTokens = true,
                    RequireExpirationTime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningToken = new BinarySecretSecurityToken(hmac.Key)
                };

            var jwtHandler = new JwtSecurityTokenHandler();

            var jwt = new JwtSecurityToken(_issuer, clientId, ticket.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);

            jwtOnTheWire = jwtHandler.WriteToken(jwt);

            SecurityToken validatedToken = null;
            jwtHandler.ValidateToken(jwtOnTheWire, validationParams,out validatedToken);
            if (validatedToken == null)
                return "token_validation_failed";

        }
        return jwtOnTheWire;

Token Consumption\\validation ASP.Net 5 vNext site within Owin Startup.cs Owin Startup.cs中的令牌消费\\验证ASP.Net 5 vNext网站

public void ConfigureServices(IServiceCollection services) 公共无效ConfigureServices(IServiceCollection服务)

services.ConfigureOAuthBearerAuthentication(config =>
        {

            //oauth validation
            var clientSecret = "not the real secret";

            var hmac = new HMACSHA256(Convert.FromBase64String(clientSecret));
            var signingCredentials = new SigningCredentials(
                new SymmetricSecurityKey(hmac.Key), Algorithms.HmacSha256Signature, Algorithms.Sha256Digest);

            config.TokenValidationParameters.ValidAudience = "myappname";
            config.TokenValidationParameters.ValidIssuer = "mydomain.com";
            config.TokenValidationParameters.RequireSignedTokens = true;
            config.TokenValidationParameters.RequireExpirationTime = true;
            config.TokenValidationParameters.ValidateLifetime = true;
            config.TokenValidationParameters.ValidateIssuerSigningKey = true;
            config.TokenValidationParameters.ValidateSignature = true;
            config.TokenValidationParameters.ValidateAudience = true;
            config.TokenValidationParameters.IssuerSigningKey = signingCredentials.SigningKey;
        });

public void Configure(IApplicationBuilder app) 公共无效配置(IApplicationBuilder应用)

app.UseOAuthBearerAuthentication(config =>
            {

                config.AuthenticationScheme = "Bearer";
                config.AutomaticAuthentication = true;
            });

I was able to add my own signature validation to the TokenValidationParameters Then I compared the incoming Raw signature of the JWT to the compiled signature in this code and if it matches the signature is valid. 我能够将自己的签名验证添加到TokenValidationParameters中,然后将传入的JWT Raw签名与此代码中的已编译签名进行了比较,如果匹配,则该签名有效。

Why this didn't happen using the builtin signature validation is beyond me, maybe it's a possible bug in beta 6 of the vNext Identity token framework. 为什么使用内置签名验证没有发生这种情况超出了我的范围,也许这可能是vNext Identity令牌框架的beta 6中的一个错误。

public void ConfigureServices(IServiceCollection services) 公共无效ConfigureServices(IServiceCollection服务)

config.TokenValidationParameters.SignatureValidator =
                delegate (string token, TokenValidationParameters parameters)
                {
                    var clientSecret = "not the real secret";

                    var jwt = new JwtSecurityToken(token);

                    var hmac = new HMACSHA256(Convert.FromBase64String(clientSecret));

                    var signingCredentials = new SigningCredentials(
                       new SymmetricSecurityKey(hmac.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

                    var signKey = signingCredentials.SigningKey as SymmetricSecurityKey;


                    var encodedData = jwt.EncodedHeader + "." + jwt.EncodedPayload;
                    var compiledSignature = Encode(encodedData, signKey.Key);

                    //Validate the incoming jwt signature against the header and payload of the token
                    if (compiledSignature != jwt.RawSignature)
                    {
                        throw new Exception("Token signature validation failed.");
                    }

                    return jwt;
                };

Encode helper method 编码助手方法

 public string Encode(string input, byte[] key)
        {
            HMACSHA256 myhmacsha = new HMACSHA256(key);
            byte[] byteArray = Encoding.UTF8.GetBytes(input);
            MemoryStream stream = new MemoryStream(byteArray);
            byte[] hashValue = myhmacsha.ComputeHash(stream);
            return Base64UrlEncoder.Encode(hashValue);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM