public Jwks GetJwks()
        {
            _rsa.ImportRSAPublicKey(_publicKey, out _);

            RsaSecurityKey key = new RsaSecurityKey(_rsa);

            var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);

            jwk.Alg = "RSA256";
            jwk.Kid = _kid;
            jwk.Use = "sig";
            var jwks = new Jwks
            {
                keys = new[] {
                    new { alg = jwk.Alg, e = jwk.E, kid = jwk.Kid, kty = jwk.Kty, n = jwk.N, use = jwk.Use }
                }
            };

            return(jwks);

            //var jwksJson = JsonSerializer.Serialize(Jwks);

            //return jwksJson;
        }
Beispiel #2
0
        public void ConvertX509SecurityKeyAsRsaSecurityKeyToJsonWebKey(JsonWebKeyConverterTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.ConvertX509SecurityKeyToJsonWebKeyTheoryData", theoryData);

            try
            {
                var convertedKey = JsonWebKeyConverter.ConvertFromX509SecurityKey(theoryData.SecurityKey as X509SecurityKey, theoryData.RepresentAsRsaKey);

                theoryData.ExpectedException.ProcessNoException(context);
                IdentityComparer.AreEqual(convertedKey, theoryData.JsonWebKey, context);

                var expectedConvertedKeyType = theoryData.RepresentAsRsaKey == true ? typeof(RsaSecurityKey) : typeof(X509SecurityKey);
                if (convertedKey.ConvertedSecurityKey.GetType() != expectedConvertedKeyType)
                {
                    context.AddDiff($"convertedKey.ConvertedSecurityKey.GetType(): '{convertedKey.ConvertedSecurityKey.GetType()}' != expectedConvertedKeyType: '{expectedConvertedKeyType}'.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Beispiel #3
0
        public static void Run()
        {
            var tokenHandler = new JsonWebTokenHandler();

            // HMAC Key
            var key = AutoGeneratedHmac(64);

            // Hmac Sha256
            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}");

            // HMAC Sha 384
            key = AutoGeneratedHmac(128);
            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha384);
            Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}");

            // Hmac Sha 512
            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);
            Console.WriteLine($"{tokenHandler.CreateToken(Jwt)}{Environment.NewLine}");
            var lastJws = tokenHandler.CreateToken(Jwt);

            // Store HMAC os Filesystem, recover and test if it's valid
            var jwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(key);

            jwk.KeyId = Guid.NewGuid().ToString();
            File.WriteAllText("current-hmac.key", JsonConvert.SerializeObject(jwk));


            var storedJwk = JsonConvert.DeserializeObject <JsonWebKey>(File.ReadAllText("current-hmac.key"));

            TokenValidationParams.IssuerSigningKey = storedJwk;

            var validationResult = tokenHandler.ValidateToken(lastJws, TokenValidationParams);

            Console.WriteLine(validationResult.IsValid);
        }
        public static RootOptions UseApiKey(this RootOptions options, string algorithmName, string subject, JwtPayload customPayload, out string token, out SecurityKey privateKey)
        {
            if (null == options.Authentication)
            {
                options.Authentication = new AuthenticationOptions();
            }

            if (null == options.Authentication.MonitorApiKey)
            {
                options.Authentication.MonitorApiKey = new MonitorApiKeyOptions();
            }

            SigningCredentials signingCreds;
            JsonWebKey         exportableJwk;

            switch (algorithmName)
            {
            case SecurityAlgorithms.EcdsaSha256:
            case SecurityAlgorithms.EcdsaSha256Signature:
            case SecurityAlgorithms.EcdsaSha384:
            case SecurityAlgorithms.EcdsaSha384Signature:
            case SecurityAlgorithms.EcdsaSha512:
            case SecurityAlgorithms.EcdsaSha512Signature:
                ECDsa            ecDsa    = ECDsa.Create(GetEcCurveFromName(algorithmName));
                ECDsaSecurityKey ecSecKey = new ECDsaSecurityKey(ecDsa);
                signingCreds = new SigningCredentials(ecSecKey, algorithmName);
                ECDsa            pubEcDsa    = ECDsa.Create(ecDsa.ExportParameters(false));
                ECDsaSecurityKey pubEcSecKey = new ECDsaSecurityKey(pubEcDsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(pubEcSecKey);
                privateKey    = ecSecKey;
                break;

            case SecurityAlgorithms.RsaSha256:
            case SecurityAlgorithms.RsaSha256Signature:
            case SecurityAlgorithms.RsaSha384:
            case SecurityAlgorithms.RsaSha384Signature:
            case SecurityAlgorithms.RsaSha512:
            case SecurityAlgorithms.RsaSha512Signature:
                RSA            rsa       = RSA.Create(GetRsaKeyLengthFromName(algorithmName));
                RsaSecurityKey rsaSecKey = new RsaSecurityKey(rsa);
                signingCreds = new SigningCredentials(rsaSecKey, algorithmName);
                RSA            pubRsa       = RSA.Create(rsa.ExportParameters(false));
                RsaSecurityKey pubRsaSecKey = new RsaSecurityKey(pubRsa);
                exportableJwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(pubRsaSecKey);
                privateKey    = rsaSecKey;
                break;

            case SecurityAlgorithms.HmacSha256:
            case SecurityAlgorithms.HmacSha384:
            case SecurityAlgorithms.HmacSha512:
                HMAC hmac = HMAC.Create(GetHmacAlgorithmFromName(algorithmName));
                SymmetricSecurityKey hmacSecKey = new SymmetricSecurityKey(hmac.Key);
                signingCreds  = new SigningCredentials(hmacSecKey, algorithmName);
                exportableJwk = JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(hmacSecKey);
                privateKey    = hmacSecKey;
                break;

            default:
                throw new ArgumentException($"Algorithm name '{algorithmName}' not supported", nameof(algorithmName));
            }

            JwtHeader               newHeader    = new JwtHeader(signingCreds, null, JwtConstants.HeaderType);
            JwtSecurityToken        newToken     = new JwtSecurityToken(newHeader, customPayload);
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string resultToken = tokenHandler.WriteToken(newToken);

            JsonSerializerOptions serializerOptions = JsonSerializerOptionsFactory.Create(JsonSerializerOptionsFactory.JsonIgnoreCondition.WhenWritingNull);
            string publicKeyJson = JsonSerializer.Serialize(exportableJwk, serializerOptions);

            string publicKeyEncoded = Base64UrlEncoder.Encode(publicKeyJson);

            options.Authentication.MonitorApiKey.Subject   = subject;
            options.Authentication.MonitorApiKey.PublicKey = publicKeyEncoded;

            token = resultToken;

            return(options);
        }
        public JwtRequestAuthorizeTests()
        {
            IdentityModelEventSource.ShowPII = true;

            _rsaKey = CryptoHelper.CreateRsaSecurityKey();

            _mockPipeline.Clients.AddRange(new Client[]
            {
                _client = new Client
                {
                    ClientName           = "Client with keys",
                    ClientId             = "client",
                    Enabled              = true,
                    RequireRequestObject = true,

                    RedirectUris = { "https://client/callback" },

                    ClientSecrets =
                    {
                        new Secret
                        {
                            // x509 cert as base64 string
                            Type  = IdentityServerConstants.SecretTypes.X509CertificateBase64,
                            Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert))
                        },
                        new Secret
                        {
                            // symmetric key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = _symmetricJwk
                        },
                        new Secret
                        {
                            // RSA key as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromRSASecurityKey(_rsaKey))
                        },
                        new Secret
                        {
                            // x509 cert as JWK
                            Type  = IdentityServerConstants.SecretTypes.JsonWebKey,
                            Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromX509SecurityKey(new X509SecurityKey(TestCert.Load())))
                        }
                    },

                    AllowedGrantTypes = GrantTypes.Implicit,

                    AllowedScopes = new List <string>
                    {
                        "openid", "profile", "api1", "api2"
                    }
                },
            });

            _mockPipeline.Users.Add(new TestUser
            {
                SubjectId = "bob",
                Username  = "******",
                Claims    = new Claim[]
                {
                    new Claim("name", "Bob Loblaw"),
                    new Claim("email", "*****@*****.**"),
                    new Claim("role", "Attorney")
                }
            });

            _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email()
            });
            _mockPipeline.ApiScopes.AddRange(new ApiResource[] {
                new ApiResource
                {
                    Name   = "api",
                    Scopes =
                    {
                        new Scope
                        {
                            Name = "api1"
                        },
                        new Scope
                        {
                            Name = "api2"
                        }
                    }
                }
            });

            _mockPipeline.Initialize();
        }
Beispiel #6
0
        private JsonWebKey GenerateRsa()
        {
            var key = CryptoService.CreateRsaSecurityKey();

            return(JsonWebKeyConverter.ConvertFromRSASecurityKey(key));
        }
Beispiel #7
0
        private JsonWebKey GenerateAES(Algorithm algorithms)
        {
            var key = CryptoService.CreateAESSecurityKey(algorithms);

            return(JsonWebKeyConverter.ConvertFromSymmetricSecurityKey(new SymmetricSecurityKey(key.Key)));
        }
Beispiel #8
0
 public DefaultJwtProvider(IOptions <JwtOptions> options)
 {
     _options   = options.Value;
     JsonWebKey = JsonWebKeyConverter
                  .ConvertFromX509SecurityKey(_options.SecurityKey);
 }