且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-12 07:40:25

我能够将自己的签名验证添加到 TokenValidationParameters 中,然后将传入的JWT Raw签名与编译后的签名进行比较在此代码中,如果匹配,则签名有效.

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.

为什么使用内置签名验证没有发生这种情况,这可能是vNext Identity令牌框架的beta 6中的一个可能的错误.

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.

public void 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;
                };

编码助手方法

 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);
        }