关于c#:OAuth承载令牌身份验证未通过签名验证

OAuth Bearer token Authentication is not passing signature validation

我在令牌使用者上得到以下错误。任何解决这一问题的帮助都将不胜感激。谢谢。

"IDX10503: Signature validation failed.

Keys tried:
'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'. 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) '. token:
'token info was here'"

OAuth服务器上的令牌生成代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 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;

令牌使用验证owin startup.cs中的ASP.NET 5 VNext站点

公共void配置服务(ISeviceCollection服务)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
        });

公共void配置(IApplicationBuilder应用程序)

1
2
3
4
5
6
app.UseOAuthBearerAuthentication(config =>
            {

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

我可以将自己的签名验证添加到tokenvalidationParameters中,然后将JWT的传入原始签名与此代码中编译的签名进行比较,如果匹配,则该签名有效。

为什么使用内置签名验证没有发生这种情况超出了我的理解,也许这是VNext身份令牌框架的beta 6中的一个可能的错误。

公共void配置服务(ISeviceCollection服务)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
                };

编码助手方法

1
2
3
4
5
6
7
8
 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);
        }