使用System.IdentityModel.Tokens.Jwt使用RS512验证JWT签名

时间:2016-10-08 14:26:47

标签: c# encryption token jwt public-key-encryption

我想使用公钥使用RS512算法验证JWT签名。我喜欢下面链接中给出的确切解决方案,它工作得很好。

Verifying JWT signed with the RS256 algorithm using public key in C#

但我想在我的应用程序中使用System.IdentityModel.Tokens.Jwt。任何人都可以通过实现System.IdentityModel.Tokens.Jwt来改变以下工作示例吗?

 static void Main(string[] args)
        {

            var token = "eyJhbGciOiJSUzUxMiIsImtpZCI6ImsxMDY5NDgxOTAifQ.eyJleHAiOjE0NzMzNDcxODUsInN1YiI6ImZmZmZmZmZmNTcxZGJkNjBlNGIwMWYyNzk4ZGI5N2Y4Iiwic2Vzc2lkIjoiNzZlNTg4ZDIzZmM3NDBiMGFkNzIxMDk2MGYwOWFhY2IiLCJ0eXBlIjoiYXQiLCJpYXQiOjE0NzMzMzYzODV9.WA-5NFaDx38dDEbZTH_hEYpbhuC3yTA9RHCmyF3Z8L1eYmZ8w4RFv5PrjWN-HprkMP7WzVfwKeSCqU4O1_FGbl88arCgZb_Ui7VUxwftRDMErib8XFu4hGfRKrdZOOHxBY_EGLINLobYG-n0akRTycIjmH0sgroQ_3Na7sxCJSM";
            var secretKey = "j6Dtct-hCbacNoaTWVskOLh7Fcj4snuQ2kY3ZIpOZfJP-fsBgj6dxUFiqZSKjHikk73xiVLAb6w2SqQ8Z2Ez5hpGmG0U3eZzWkm8gwrpN-DN3eSBjBzyE5UUSTxmfMXGIBZtlwGEmmameycvX8nCJLuF83nK7Q5OQd7MIWUw-_8";
            bool isValied = false;

            string[] tokenParts = token.Split('.');

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(
              new RSAParameters()
              {
                  Modulus = FromBase64Url(secretKey),
                  Exponent = FromBase64Url("AQAB")
              });

            HashAlgorithm H = SHA512.Create();
            byte[] hash = H.ComputeHash(Encoding.UTF8.GetBytes(tokenParts[0] + '.' + tokenParts[1]));

            RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
            rsaDeformatter.SetHashAlgorithm(H.GetType().ToString());
            if (rsaDeformatter.VerifySignature(hash, FromBase64Url(tokenParts[2])))
                isValied = true;




        }

        static byte[] FromBase64Url(string base64Url)
        {
            string padded = base64Url.Length % 4 == 0
                ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
            string base64 = padded.Replace("_", "/")
                                  .Replace("-", "+");
            return Convert.FromBase64String(base64);
        }

1 个答案:

答案 0 :(得分:2)

使用最新版本的System.IdentityModel.Tokens.Jwt(5.0.0)并假设您需要验证以下JWT令牌:

  

eyJhbGciOiJSUzUxMiIsImtpZCI6IjhDOURCQzA1OEIzN0Y5NzM2QzdCMzVGMDVFMDcxOENDMDUzOUU4RDciLCJ0eXAiOiJKV1QifQ.eyJuYmYiOjE0NzYxNzg2NzMsImV4cCI6MTQ3NjE4MjI3MywiaWF0IjoxNDc2MTc4NjczLCJpc3MiOiJNRSIsImF1ZCI6IllPVSJ9.Lh0iXDREkrgfuPBAJxOlNcoctRQkAV-VuhvH4oqavSV8M5ZYKhkSJ_11FyRN24yRTZfdScbOGZwO_-7Z8qSAbeLOc5HNa52LN09si-gruQFoB2Fikvd5FhwC5tqpqZeNw6usFR05Z9hl0SV05-joDv3OVfpnl31figrNiXcgqo2bB9kEPo6XeOw_JVTOrta6bHI-q6uulc4ZrLF4UWosb5R5ALLN5hwsY2lX9LrSCLfhuMlEDyjBbvrhC5fr29Ci9NYmk4U75qhhf13nS69vX8RJ5xRW8Nw6MP3Om0WaW-yX0RhtdrGZ8GuqdOxWU25i3j_qj5-ovO3OAhh0qsdMBA

使用RS512(通过在jwt.io在线解码查看完整的令牌内容),然后您可以执行以下操作:

string thumbprint = "8C9DBC058B37F9736C7B35F05E0718CC0539E8D7"; // Change to your certificate

X509Certificate2 certificate = GetSigningCertificate(thumbprint);

var handler = new JwtSecurityTokenHandler();

string jwt = "[TOKEN_TO_BE_VALIDATED]";

SecurityToken token;
ClaimsPrincipal principal = handler.ValidateToken(jwt, new TokenValidationParameters
{
    ValidIssuer = "ME",
    ValidAudience = "YOU",
    IssuerSigningKey = new X509SecurityKey(certificate),
}, out token);