示例#1
0
        /// <summary>
        /// Convert JsonWebKeySet to List<SecurityKey>
        /// </summary>
        /// <param name="jsonWebKeySet">IdentityModel.Jwk.JsonWebKeySet</param>
        /// <returns>SecurityKey list</returns>
        private static List <SecurityKey> getSecurityKeys(IdentityModel.Jwk.JsonWebKeySet jsonWebKeySet)
        {
            var keys = new List <SecurityKey>();

            foreach (var key in jsonWebKeySet.Keys)
            {
                if (key.Kty == "RSA")
                {
                    if (key.X5c != null && key.X5c.Count() > 0)
                    {
                        string certificateString = key.X5c[0];
                        var    certificate       = new X509Certificate2(Convert.FromBase64String(certificateString));

                        var x509SecurityKey = new X509SecurityKey(certificate)
                        {
                            KeyId = key.Kid
                        };

                        keys.Add(x509SecurityKey);
                    }
                    else if (!string.IsNullOrWhiteSpace(key.E) && !string.IsNullOrWhiteSpace(key.N))
                    {
                        byte[] exponent = fromBase64Url(key.E);
                        byte[] modulus  = fromBase64Url(key.N);

                        var rsaParameters = new RSAParameters
                        {
                            Exponent = exponent,
                            Modulus  = modulus
                        };

                        var rsaSecurityKey = new RsaSecurityKey(rsaParameters)
                        {
                            KeyId = key.Kid
                        };

                        keys.Add(rsaSecurityKey);
                    }
                    else
                    {
                        throw new Exception("JWK data is missing in token validation");
                    }
                }
                else
                {
                    throw new NotImplementedException("Only RSA key type is implemented for token validation");
                }
            }

            return(keys);
        }
示例#2
0
        public static IdentityModel.Jwk.JsonWebKeySet CreateKeySet(RsaSecurityKey key)
        {
            var parameters = key.Rsa?.ExportParameters(false) ?? key.Parameters;
            var exponent   = Base64Url.Encode(parameters.Exponent);
            var modulus    = Base64Url.Encode(parameters.Modulus);

            var webKey = new IdentityModel.Jwk.JsonWebKey
            {
                Kty = "RSA",
                Use = "sig",
                Kid = key.KeyId,
                E   = exponent,
                N   = modulus,
            };

            var set = new IdentityModel.Jwk.JsonWebKeySet();

            set.Keys.Add(webKey);
            return(set);
        }
示例#3
0
        private ClaimsPrincipal ValidateSignature(
            string identityToken,
            JwtSecurityTokenHandler handler,
            TokenValidationParameters parameters,
            IdentityModel.Jwk.JsonWebKeySet keySet)
        {
            if (parameters.RequireSignedTokens)
            {
                // read keys from provider information
                var keys = new List <SecurityKey>();

                foreach (var webKey in keySet.Keys)
                {
                    if (webKey.E.IsPresent() && webKey.N.IsPresent())
                    {
                        // only add keys used for signatures
                        if (webKey.Use == "sig" || webKey.Use == null)
                        {
                            var e = Base64Url.Decode(webKey.E);
                            var n = Base64Url.Decode(webKey.N);

                            var key = new RsaSecurityKey(new RSAParameters {
                                Exponent = e, Modulus = n
                            });
                            key.KeyId = webKey.Kid;

                            keys.Add(key);

                            _logger.LogDebug("Added signing key with kid: {kid}", key?.KeyId ?? "not set");
                        }
                    }
                    else if (webKey.X.IsPresent() && webKey.Y.IsPresent() && webKey.Crv.IsPresent())
                    {
                        var ec = ECDsa.Create(new ECParameters
                        {
                            Curve = GetCurveFromCrvValue(webKey.Crv),
                            Q     = new ECPoint
                            {
                                X = Base64Url.Decode(webKey.X),
                                Y = Base64Url.Decode(webKey.Y)
                            }
                        });

                        var key = new ECDsaSecurityKey(ec);
                        key.KeyId = webKey.Kid;

                        keys.Add(key);
                    }
                    else
                    {
                        _logger.LogDebug("Signing key with kid: {kid} currently not supported",
                                         webKey.Kid ?? "not set");
                    }
                }

                parameters.IssuerSigningKeys = keys;
            }

            SecurityToken token;

            return(handler.ValidateToken(identityToken, parameters, out token));
        }
        public static List <SecurityKey> GetSigningKeys(this IdentityModel.Jwk.JsonWebKeySet jwks)
        {
            var securityKeyList = new List <SecurityKey>();

            foreach (var key in jwks.Keys)
            {
                if (!StringComparer.Ordinal.Equals(key.Kty, "RSA") || (!string.IsNullOrWhiteSpace(key.Use) && !StringComparer.Ordinal.Equals(key.Use, "sig")))
                {
                    continue;
                }
                if (key.X5c != null)
                {
                    foreach (var s in key.X5c)
                    {
                        try
                        {
                            SecurityKey securityKey = new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(s)));
                            securityKey.KeyId = key.Kid;
                            securityKeyList.Add(securityKey);
                        }
                        catch (CryptographicException ex)
                        {
                            throw new InvalidOperationException($"Unable to create an X509Certificate2 from the X509Data: '{s}'. See inner exception for additional details.", ex);
                        }
                        catch (FormatException ex)
                        {
                            throw new InvalidOperationException($"Unable to create an X509Certificate2 from the X509Data: '{s}'. See inner exception for additional details.", ex);
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(key.E))
                {
                    continue;
                }
                {
                    if (string.IsNullOrWhiteSpace(key.N))
                    {
                        continue;
                    }
                    try
                    {
                        var rsaParameters = new RSAParameters
                        {
                            Exponent = Base64UrlEncoder.DecodeBytes(key.E),
                            Modulus  = Base64UrlEncoder.DecodeBytes(key.N)
                        };
                        SecurityKey securityKey = new RsaSecurityKey(rsaParameters);
                        securityKey.KeyId = key.Kid;
                        securityKeyList.Add(securityKey);
                    }
                    catch (CryptographicException ex)
                    {
                        throw new InvalidOperationException($"Unable to create an RSA public key from the Exponent and Modulus found in the JsonWebKey: E: '{key.E}', N: '{key.N}'. See inner exception for additional details.", ex);
                    }
                    catch (FormatException ex)
                    {
                        throw new InvalidOperationException($"Unable to create an RSA public key from the Exponent and Modulus found in the JsonWebKey: E: '{key.E}', N: '{key.N}'. See inner exception for additional details.", ex);
                    }
                }
            }

            return(securityKeyList);
        }