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

后端 未结 6 608
遥遥无期
遥遥无期 2020-11-27 12:26

Ok, I understand that the question I am asking may be pretty obvious, but unfortunately I lack the knowledge on this subject and this task seems to be quite tricky for me.

6条回答
  •  隐瞒了意图╮
    2020-11-27 13:05

    For anyone that is looking for a quick method to validate RS256 with a public key that has "-----BEGIN PUBLIC KEY-----"/"-----END PUBLIC KEY------"

    Here are two methods with the help of BouncyCastle.

        public bool ValidateJasonWebToken(string fullKey, string jwtToken)
        {
            try
            {
                var rs256Token = fullKey.Replace("-----BEGIN PUBLIC KEY-----", "");
                rs256Token = rs256Token.Replace("-----END PUBLIC KEY-----", "");
                rs256Token = rs256Token.Replace("\n", "");
    
                Validate(jwtToken, rs256Token);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
        }
    
        private void Validate(string token, string key)
        {
            var keyBytes = Convert.FromBase64String(key); // your key here
    
            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
            RSAParameters rsaParameters = new RSAParameters
            {
                Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
                Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
            };
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParameters);
                var validationParameters = new TokenValidationParameters()
                {
                    RequireExpirationTime = false,
                    RequireSignedTokens = true,
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    IssuerSigningKey = new RsaSecurityKey(rsa)
                };
                var handler = new JwtSecurityTokenHandler();
                var result = handler.ValidateToken(token, validationParameters, out var validatedToken);
            }
        }
    

    This is a combination of http://codingstill.com/2016/01/verify-jwt-token-signed-with-rs256-using-the-public-key/ and @olaf answer that uses system.IdentityModel.Tokens.Jwt

提交回复
热议问题