public async Task ShouldGenerateAndValidateJweAndJws()
    {
        await WarmupData.Clear();

        var handler = new JsonWebTokenHandler();
        var now     = DateTime.Now;

        // Generate right now and in memory
        var newKey = new CryptographicKey(Algorithm.Create(AlgorithmType.RSA, JwtType.Both));

        var encryptingCredentials = new EncryptingCredentials(newKey, EncryptionAlgorithmKey.RsaOAEP, EncryptionAlgorithmContent.Aes128CbcHmacSha256);
        var signingCredentials    = new SigningCredentials(newKey, DigitalSignaturesAlgorithm.RsaSsaPssSha256);

        var claims        = new ClaimsIdentity(GenerateClaim().Generate(5));
        var descriptorJws = new SecurityTokenDescriptor
        {
            Issuer             = "me",
            Audience           = "you",
            IssuedAt           = now,
            NotBefore          = now,
            Expires            = now.AddMinutes(5),
            Subject            = claims,
            SigningCredentials = signingCredentials
        };
        var descriptorJwe = new SecurityTokenDescriptor
        {
            Issuer                = "me",
            Audience              = "you",
            IssuedAt              = now,
            NotBefore             = now,
            Expires               = now.AddMinutes(5),
            Subject               = claims,
            EncryptingCredentials = encryptingCredentials
        };

        var jws = handler.CreateToken(descriptorJws);
        var jwe = handler.CreateToken(descriptorJwe);

        var result = await handler.ValidateTokenAsync(jws,
                                                      new TokenValidationParameters
        {
            ValidIssuer      = "me",
            ValidAudience    = "you",
            IssuerSigningKey = signingCredentials.Key
        });

        result.IsValid.Should().BeTrue();

        result = await handler.ValidateTokenAsync(jwe,
                                                  new TokenValidationParameters
        {
            ValidIssuer         = "me",
            ValidAudience       = "you",
            RequireSignedTokens = false,
            TokenDecryptionKey  = encryptingCredentials.Key
        });

        result.IsValid.Should().BeTrue();
    }
Esempio n. 2
0
        private static string CreatePssToken()
        {
            var jwt = handler.CreateToken(descriptor);

            Console.WriteLine(jwt);

            return(jwt);
        }
        public void ShouldValidateJweAndJws()
        {
            var options = new JwksOptions()
            {
                KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_",
            };

            var encryptingCredentials = _jwksService.GenerateEncryptingCredentials(options);
            var signingCredentials    = _jwksService.GenerateSigningCredentials(options);

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwtE    = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(GenerateClaim().Generate(5)),
                EncryptingCredentials = encryptingCredentials
            };
            var jwtS = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };


            var jwe = handler.CreateToken(jwtE);
            var jws = handler.CreateToken(jwtS);

            var jweResult = handler.ValidateToken(jwe,
                                                  new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = encryptingCredentials.Key
            });
            var jwsResult = handler.ValidateToken(jws,
                                                  new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = encryptingCredentials.Key
            });

            jweResult.IsValid.Should().BeTrue();
        }
        private static string GetSignedClientAssertionUsingWilson(
            string issuer,
            string aud,
            X509Certificate2 cert)
        {
            // no need to add exp, nbf as JsonWebTokenHandler will add them by default.
            var claims = new Dictionary <string, object>()
            {
                { "aud", aud },
                { "iss", issuer },
                { "jti", Guid.NewGuid().ToString() },
                { "sub", issuer }
            };

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                SigningCredentials = new X509SigningCredentials(cert)
            };

            var handler = new JsonWebTokenHandler();
            var signedClientAssertion = handler.CreateToken(securityTokenDescriptor);

            return(signedClientAssertion);
        }
Esempio n. 5
0
        public MeasureDifferentAlgorithms()
        {
            IdentityModelEventSource.ShowPII = true;
            CryptoProviderFactory.DefaultCacheSignatureProviders = false;
            _jwtTokenEcd256       = _jsonWebTokenHandler.CreateToken(TestData.SecurityTokenDescriptor(TestData.EcdSigningCredentials_2048Sha256));
            _jwtTokenEcd512       = _jsonWebTokenHandler.CreateToken(TestData.SecurityTokenDescriptor(TestData.EcdSigningCredentials_2048Sha512));
            _jwtTokenRsa256       = _jsonWebTokenHandler.CreateToken(TestData.SecurityTokenDescriptor(TestData.RsaSigningCredentials_2048Sha256));
            _jwtTokenRsa512       = _jsonWebTokenHandler.CreateToken(TestData.SecurityTokenDescriptor(TestData.RsaSigningCredentials_2048Sha512));
            _jwtTokenSymmetric256 = _jsonWebTokenHandler.CreateToken(TestData.SecurityTokenDescriptor(TestData.SymmetricSigningCreds_256Sha256));

            _tokenValidationParametersEcd256       = TestData.TokenValidationParameters(TestData.EcdSigningCredentials_2048Sha256.Key);
            _tokenValidationParametersEcd512       = TestData.TokenValidationParameters(TestData.EcdSigningCredentials_2048Sha512.Key);
            _tokenValidationParametersRsa256       = TestData.TokenValidationParameters(TestData.RsaSigningCredentials_2048Sha512.Key);
            _tokenValidationParametersRsa512       = TestData.TokenValidationParameters(TestData.RsaSigningCredentials_2048Sha512.Key);
            _tokenValidationParametersSymmetric256 = TestData.TokenValidationParameters(TestData.SymmetricSigningCreds_256Sha256.Key);
        }
Esempio n. 6
0
        public string GenerateUserToken(User user)
        {
            byte[] key           = Encoding.ASCII.GetBytes(_configuration["Auth:TokenSecret"]);
            var    tokenHandle   = new JsonWebTokenHandler();
            int    tokenDurHours = _configuration.GetValue <int>("Auth:TokenDuration");

            string[] userRoles = user.Roles.Select(u => u.Role.Name).ToArray();

            var claims = new Dictionary <string, object>
            {
                { nameof(User.Id), user.Id },
                { nameof(User.Name), user.Name },
                { nameof(User.Group), user.Group },
                { "Roles", userRoles }
            };

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                Expires            = DateTime.UtcNow.AddHours(tokenDurHours),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            string token = tokenHandle.CreateToken(tokenDescriptor);

            Console.WriteLine(token);
            return(token);
        }
Esempio n. 7
0
        private static string GetSignedClientAssertion(string tenantId, string confidentialClientID,
                                                       string certificatePath, string certPass)
        {
            var cert = new X509Certificate2(certificatePath, certPass, X509KeyStorageFlags.EphemeralKeySet);

            // JsonWebTokenHandler will add defaults
            var claims = new Dictionary <string, object>()
            {
                { "aud", $"https://login.microsoftonline.com/{tenantId}/oauth2/token" },
                { "iss", confidentialClientID },
                { "jti", Guid.NewGuid().ToString() },
                { "sub", confidentialClientID }
            };

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Claims             = claims,
                SigningCredentials = new X509SigningCredentials(cert)
            };

            var handler = new JsonWebTokenHandler();
            var signedClientAssertion = handler.CreateToken(securityTokenDescriptor);

            return(signedClientAssertion);
        }
Esempio n. 8
0
        /// <summary>
        /// Generates token by given model.
        /// Validates whether the given model is valid, then gets the assymmetric private key.
        /// Encrypt the token and returns it.
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Generated token.</returns>
        public string GenerateToken(IAuthContainerModel model)
        {
            if (model == null || model.Claims == null || model.Claims.Length == 0 || model.SecretKey == null)
            {
                throw new ArgumentException("Arguments to create token are not valid.");
            }


            SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Audience = "Audience",
                Issuer   = "Issuer",
                AdditionalHeaderClaims = new Dictionary <string, object>()
                {
                    { "x5ts", SecretKey }
                },
                NotBefore          = DateTime.Now,
                Expires            = DateTime.Now.AddMinutes(Convert.ToInt32(model.ExpireMinutes)),
                Subject            = new ClaimsIdentity(model.Claims),
                SigningCredentials = new SigningCredentials(GetPrivateKeyfromCertificate(), model.SecurityAlgorithm)
            };

            //var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
            //string token = jwtSecurityTokenHandler.WriteToken(securityToken);

            var token = jsontoken.CreateToken(securityTokenDescriptor);

            return(token);
        }
Esempio n. 9
0
        /// <summary>
        /// Generate JWT
        /// </summary>
        /// <returns></returns>
        internal string GenerateToken()
        {
            try
            {
                // ... Build ClaimSet
                var claims = new ClaimsIdentity(new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Sub, AppId)
                });

                // ... Build Token Descriptor
                var securityTokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = claims,
                    Audience           = EndPoint,
                    Issuer             = AppId,
                    NotBefore          = DateTime.Now,
                    Expires            = DateTime.Now.AddMinutes(ExpiryMinutes),
                    SigningCredentials = new X509SigningCredentials(X509Cert)
                };

                // ... Build JWT Token
                var handler = new JsonWebTokenHandler();
                return(handler.CreateToken(securityTokenDescriptor));
            }
            catch (Exception ex)
            {
                throw new Exception("Failed in Generate JWT, error " + ex.Message);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Create a new client secret (per request).
        /// </summary>
        /// <param name="issuer">Your account's team ID found in the dev portal.</param>
        /// <param name="audience">Apple authority.</param>
        /// <param name="subject">The service id (client_id).</param>
        /// <param name="privateKey">Base64 encoded private key.</param>
        /// <param name="privateKeyId">The key id.</param>
        /// <param name="duration">Expiry can be a maximum of 6 months - generate one per request or re-use until expiration. Defaults to 5 minutes.</param>
        public static string CreateNewToken(string issuer, string audience, string subject, string privateKey, string privateKeyId, TimeSpan?duration = null)
        {
            duration ??= TimeSpan.FromMinutes(5);
            var now   = DateTime.UtcNow;
            var ecdsa = ECDsa.Create();

            if (privateKey.StartsWith('-'))
            {
                var lines = privateKey.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                privateKey = string.Join("", lines.Skip(1).Take(lines.Length - 2));
            }
//#if NETCOREAPP3_1
            ecdsa?.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKey), out _);
//#else
            //ecdsa?.ImportFromPem(privateKey);
//#endif
            var handler = new JsonWebTokenHandler();
            var key     = new ECDsaSecurityKey(ecdsa)
            {
                KeyId = privateKeyId
            };

            return(handler.CreateToken(new SecurityTokenDescriptor {
                Issuer = issuer,
                Audience = audience,
                Claims = new Dictionary <string, object> {
                    { "sub", subject }
                },
                Expires = now.Add(duration.Value),
                IssuedAt = now,
                NotBefore = now,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256)
            }));
        }
Esempio n. 11
0
        public static string GetToken(IEnumerable <string>?roles = null, IEnumerable <string>?scopes = null)
        {
            roles ??= Array.Empty <string>();
            scopes = new[] { "user_impersonation" }.Concat(scopes ?? Array.Empty <string>());

            var tokenHandler = new JsonWebTokenHandler();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience = "tests",
                Issuer   = "tests",
                Claims   = new Dictionary <string, object>
                {
                    ["name"]        = "Testy McTesterson",
                    ["given_name"]  = "Testy",
                    ["family_name"] = "McTesterson",
                    ["unique_name"] = "*****@*****.**",
                    ["upn"]         = "*****@*****.**",
                    ["acr"]         = "1",
                    ["amr"]         = new[] { "pwd", "mfa" },
                    ["roles"]       = roles.ToArray(),
                    ["oid"]         = PrincipalId.ToString(),
                    ["appid"]       = Guid.NewGuid().ToString(),
                    ["deviceid"]    = Guid.NewGuid().ToString(),
                    ["sub"]         = "Xwq2sQJEYUbxkwV_0V9Gg_nIAW2mWX9tJnt_Gqrkdbm",
                    ["tid"]         = Guid.NewGuid().ToString(),
                    ["scp"]         = string.Join(" ", scopes),
                    ["ver"]         = "1.0",
                },
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SigningKey)), SecurityAlgorithms.HmacSha256Signature),
            };

            return(tokenHandler.CreateToken(tokenDescriptor));
        }
        public static void Run()
        {
            var tokenHandler = new JsonWebTokenHandler();
            var key          = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };

            Jwt.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSsaPssSha256);
            var lastJws = tokenHandler.CreateToken(Jwt);

            Console.WriteLine($"{lastJws}{Environment.NewLine}");

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

            File.WriteAllText("current-rsa.key", JsonConvert.SerializeObject(jwk));


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

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

            Console.WriteLine(validationResult.IsValid);
        }
Esempio n. 13
0
        public void ShouldValidateJws(string algorithm)
        {
            var signingCredentials = new SigningCredentials(new CryptographicKey(algorithm), algorithm);
            var handler            = new JsonWebTokenHandler();
            var now = DateTime.Now;
            var jwt = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jws    = handler.CreateToken(jwt);
            var result = handler.ValidateToken(jws,
                                               new TokenValidationParameters
            {
                ValidIssuer      = "me",
                ValidAudience    = "you",
                IssuerSigningKey = signingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 14
0
        public void ShouldValidateJwe(string algorithm, string encryption)
        {
            var key = new CryptographicKey(Algorithm.Create(algorithm).WithContentEncryption(encryption));
            var encryptingCredentials = new EncryptingCredentials(key, algorithm, encryption);

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwt     = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(GenerateClaim().Generate(5)),
                EncryptingCredentials = encryptingCredentials
            };

            var jwe    = handler.CreateToken(jwt);
            var result = handler.ValidateToken(jwe,
                                               new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = encryptingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 15
0
        public static void Run()
        {
            var key = new RsaSecurityKey(RSA.Create(2048))
            {
                KeyId = Guid.NewGuid().ToString()
            };
            var jweKey = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes128CbcHmacSha256);
            var payloadRepresentation = new List <Claim>()
            {
                new("claim1", "10"),
                new("claim2", "claim2-value"),
                new ("name", "Bruno Brito"),
                new ("given_name", "Bruno"),
                new ("logins", "brunohbrito"),
                new ("logins", "bhdebrito"),
                new ("logins", "bruno_hbrito"),
            };

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;
            var jwt     = new SecurityTokenDescriptor
            {
                Issuer                = "me",
                Audience              = "you",
                IssuedAt              = now,
                NotBefore             = now,
                Expires               = now.AddMinutes(5),
                Subject               = new ClaimsIdentity(payloadRepresentation),
                EncryptingCredentials = jweKey
            };

            var jwe = handler.CreateToken(jwt);

            Console.ResetColor();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write("JWE: ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(jwe);
            Console.ResetColor();


            var result = handler.ValidateToken(jwe,
                                               new TokenValidationParameters
            {
                ValidIssuer         = "me",
                ValidAudience       = "you",
                RequireSignedTokens = false,
                TokenDecryptionKey  = jweKey.Key
            });
            var claims = JsonSerializer.Serialize(result.Claims, new JsonSerializerOptions()
            {
                WriteIndented = true
            });

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Claims: ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(claims);
            Console.ResetColor();
        }
Esempio n. 16
0
        public async Task <IActionResult> Post([FromBody] UserRequestModel credentials)
        {
            ApiUser apiUser = new ApiUser(credentials.UserName);
            var     result  = await _userManager.CreateAsync(apiUser, credentials.Password);

            if (!result.Succeeded)
            {
                _logger.LogError($"User creation error: {String.Join(" | ", result.Errors.Select(x => x.Description).ToArray())}");
                throw new ApplicationException("Could not create user.");
            }

            var now          = DateTime.Now;
            var key          = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_options.SecretKey));
            var tokenHandler = new JsonWebTokenHandler();
            var descriptor   = new SecurityTokenDescriptor
            {
                Issuer    = _options.Issuer,
                IssuedAt  = now,
                NotBefore = now,
                Expires   = now.AddHours(1),
                Claims    = new Dictionary <string, object> {
                    { JwtRegisteredClaimNames.Sub, apiUser.UserName }
                },
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            };

            TegetgramUserDTO user = await _userService.GetUser(apiUser.UserName, apiUser.UserName);

            return(Ok(new
            {
                access_token = tokenHandler.CreateToken(descriptor),
                user = user
            }));
        }
Esempio n. 17
0
        public IActionResult GetJwtForChat()
        {
            Account account = _accountService.GetAccount(Guid.Parse(HttpContext.User.Identity.Name));

            var iat = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
            var exp = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)).ToUnixTimeSeconds();

            var payload = "{" +
                          "\"iat\":" + iat.ToString() + ", " +
                          "\"exp\":" + exp.ToString() + ", " +
                          "\"external_id\":\"" + account.Id.ToString() + "\", " +
                          "\"name\":\"" + account.FirstName + "\", " +
                          "\"email\":\"" + account.Email + "\"" +
                          "}";

            var jsonWebTokenHandler = new JsonWebTokenHandler();

            //var jsonWebToken = new JsonWebToken("{\"typ\":\"JWT\", \"alg\":\"HS256\"}", payload);

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["ZendeskSharedKey"]));

            var signingCredentials = new SigningCredentials(key, "HS256");

            var token = jsonWebTokenHandler.CreateToken(payload, signingCredentials);

            return(Ok(token));
        }
Esempio n. 18
0
        public static void Authorize()
        {
            var txtreader = new StringReader(Authorization.privateKey);
            var rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters) new PemReader(txtreader).ReadObject());

            var jwtsigner = new JsonWebTokenHandler();
            var now       = DateTime.UtcNow;

            var descriptor = new SecurityTokenDescriptor
            {
                Issuer   = Authorization.clientId,
                Audience = "https://xenqu.com",
                Expires  = now.AddMinutes(5),
                Claims   = new Dictionary <string, object> {
                    { "sub", Authorization.subscriber }
                },
                SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsaParams), "RS256")
            };

            var data = "grant_type=" + Uri.EscapeDataString("urn:ietf:params:oauth:grant-type:jwt-bearer") +
                       "&assertion=" + Uri.EscapeDataString(jwtsigner.CreateToken(descriptor));

            var provider = ServiceProvider.Instance;
            var results  = JObject.Parse(provider.PostData("/oauth2/token", "application/x-www-form-urlencoded", data));

            Authorization.tokenKey     = (string)results["token"];
            Authorization.tokenSecret  = (string)results["token_secret"];
            Authorization.tokenExpires = Convert.ToDouble((string)results["expires"]);
        }
        public void ShouldGetCurrentToSignAndValidateJws(string algorithm, KeyType keyType)
        {
            var options = new JwksOptions()
            {
                Jws = JwsAlgorithm.Create(algorithm, keyType), KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_"
            };

            _jwksService.GenerateSigningCredentials(options);
            var signingCredentials = _jwksService.GetCurrentSigningCredentials();
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt    = handler.CreateToken(descriptor);
            var result = handler.ValidateToken(jwt,
                                               new TokenValidationParameters
            {
                ValidIssuer      = "me",
                ValidAudience    = "you",
                IssuerSigningKey = signingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 20
0
        public void ShouldSaveDeterministicJwkRecoverAndSigning(string algorithm, KeyType keyType)
        {
            _database.SecurityKeys.RemoveRange(_database.SecurityKeys.ToList());
            _database.SaveChanges();

            var options = new JwksOptions()
            {
                Algorithm = Algorithm.Create(algorithm, keyType)
            };

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;

            // Generate right now and in memory
            var newKey = _keyService.GetCurrent(options);

            // recovered from database
            var currentKey = _keyService.GetCurrent(options);

            newKey.Kid.Should().Be(currentKey.Kid);
            var claims     = new ClaimsIdentity(GenerateClaim().Generate(5));
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = claims,
                SigningCredentials = newKey
            };
            var descriptorFromDb = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = claims,
                SigningCredentials = currentKey
            };

            var jwt1 = handler.CreateToken(descriptor);
            var jwt2 = handler.CreateToken(descriptorFromDb);

            jwt1.Should().Be(jwt2);
        }
Esempio n. 21
0
        /// <summary>
        /// Builds, signs and returns the string representation of the PoP token. The PoP token will be valid for 2 minutes.
        /// </summary>
        /// <returns> The PoP token </returns>
        /// <exception cref="PopTokenBuilderException"> if error occurs while building the PoP token </exception>
        public string Build()
        {
            try
            {
                if (_ehtsKeyValueMap == null ||
                    _ehtsKeyValueMap.Count == 0 ||
                    DoesContainAnyEmptyKeysOrValues(_ehtsKeyValueMap))
                {
                    throw new PopTokenBuilderException("The ehtsKeyValueMap should not be null or empty and should not contain any null or empty ehts keys or values");
                }

                if (_ehtsKeyValueMap.Count > MAX_NUMBER_OF_EHTS)
                {
                    throw new PopTokenBuilderException("The ehtsKeyValueMap should not contain more than " + MAX_NUMBER_OF_EHTS + " entries");
                }

                if (string.IsNullOrEmpty(_privateKeyXmlOrPemRsa))
                {
                    throw new PopTokenBuilderException("The privateKeyXmlRsa should be provided to SignWith the PoP token");
                }

                _rsaSecurityKey = PopTokenBuilderUtils.CreateRsaSecurityKey(_privateKeyXmlOrPemRsa);

                var ehts                    = BuildEhtsString(_ehtsKeyValueMap);
                var edts                    = CalculateEdtsSha256Base64Hash(_ehtsKeyValueMap);
                var jti                     = GetUniqueIdentifier();
                var version                 = Version;
                var issuedAt                = IssuedAt;
                var expires                 = GetExpiration(issuedAt);
                var signingCredentials      = new SigningCredentials(_rsaSecurityKey, SecurityAlgorithms.RsaSha256);
                var securityTokenDescriptor = new SecurityTokenDescriptor()
                {
                    Subject = new ClaimsIdentity(new List <Claim>
                    {
                        new Claim("ehts", ehts),
                        new Claim("edts", edts),
                        new Claim("v", version),
                        new Claim("jti", jti)
                    }),
                    Audience           = _audience,
                    Issuer             = _issuer,
                    NotBefore          = issuedAt,
                    IssuedAt           = issuedAt,
                    Expires            = expires,
                    SigningCredentials = signingCredentials
                };

                var jsonWebTokenHandler = new JsonWebTokenHandler();
                return(jsonWebTokenHandler.CreateToken(securityTokenDescriptor)); // Any instance members are not guaranteed to be thread safe.
            }
            catch (PopTokenBuilderException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new PopTokenBuilderException("Error occurred while building the PoP token builder, error: " + ex.Message, ex);
            }
        }
        /// <summary>
        /// Creates a token based on the passed <see cref="SecurityTokenDescriptor"/>.
        /// </summary>
        /// <param name="securityTokenDescriptor">The <see cref="SecurityTokenDescriptor"/> which describes the token to create.</param>
        /// <returns>A JWS token described by the passed <see cref="SecurityTokenDescriptor"/>.</returns>
        public static string CreateToken(SecurityTokenDescriptor securityTokenDescriptor)
        {
            var tokenHandler = new JsonWebTokenHandler()
            {
                SetDefaultTimesOnTokenCreation = false
            };

            return(tokenHandler.CreateToken(securityTokenDescriptor));
        }
        /// <summary>
        /// Creates a token based on the passed <see cref="Dictionary{string, object}"/>.
        /// </summary>
        /// <param name="securityTokenDescriptor">
        /// The <see cref="Dictionary{string, object}"/> of claims which describe the token to create.
        /// </param>
        /// <returns>A JWS token described by the passed <see cref="Dictionary{string, object}"/>.</returns>
        public string CreateToken(Dictionary <string, object> claims)
        {
            var tokenHandler = new JsonWebTokenHandler()
            {
                SetDefaultTimesOnTokenCreation = false
            };

            return(tokenHandler.CreateToken(CreateJsonPayload(claims), SigningCredentials));
        }
Esempio n. 24
0
        /// <summary>
        /// 生成 Token
        /// </summary>
        /// <param name="issuerSigningKey"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        public static string Encrypt(string issuerSigningKey, string payload)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(issuerSigningKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var tokenHandler = new JsonWebTokenHandler();

            return(tokenHandler.CreateToken(payload, credentials));
        }
    public async Task ShouldSaveDeterministicJwkRecoverAndSigning(string algorithm)
    {
        await this.WarmupData.Clear();

        var handler = new JsonWebTokenHandler();
        var now     = DateTime.Now;

        // Generate right now and in memory
        var newKey = new CryptographicKey(algorithm);
        await _store.Store(new KeyMaterial(newKey));

        // recovered from database
        var currentKey = await _store.GetCurrent();

        newKey.Key.KeyId.Should().Be(currentKey.KeyId);

        var claims     = new ClaimsIdentity(GenerateClaim().Generate(5));
        var descriptor = new SecurityTokenDescriptor
        {
            Issuer             = "me",
            Audience           = "you",
            IssuedAt           = now,
            NotBefore          = now,
            Expires            = now.AddMinutes(5),
            Subject            = claims,
            SigningCredentials = new SigningCredentials(newKey, algorithm)
        };
        var descriptorFromDb = new SecurityTokenDescriptor
        {
            Issuer             = "me",
            Audience           = "you",
            IssuedAt           = now,
            NotBefore          = now,
            Expires            = now.AddMinutes(5),
            Subject            = claims,
            SigningCredentials = new SigningCredentials(currentKey, algorithm)
        };

        var jwt1 = handler.CreateToken(descriptor);
        var jwt2 = handler.CreateToken(descriptorFromDb);

        jwt1.Should().Be(jwt2);
    }
        public static string GenerateJws(SecurityTokenDescriptor jwt)
        {
            var tokenHandler = new JsonWebTokenHandler();

            var rsaKey = GetKey();

            jwt.SigningCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256);

            return(tokenHandler.CreateToken(jwt));
        }
        public void GetClaimsFromJObject()
        {
            var context             = new CompareContext();
            var jsonWebTokenHandler = new JsonWebTokenHandler();
            var jsonWebTokenString  = jsonWebTokenHandler.CreateToken(Default.PayloadString, KeyingMaterial.JsonWebKeyRsa256SigningCredentials);
            var jsonWebToken        = new JsonWebToken(jsonWebTokenString);
            var claims = jsonWebToken.Claims;

            IdentityComparer.AreEqual(Default.PayloadClaims, claims, context);
            TestUtilities.AssertFailIfErrors(context);
        }
        public void ShouldNotBeSameJwtWhenProbabilisticToken(string algorithm, KeyType keyType)
        {
            var signingCredentials = _service.GenerateSigningCredentials(Algorithm.Create(algorithm, keyType));
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt1 = handler.CreateToken(descriptor);
            var jwt2 = handler.CreateToken(descriptor);

            jwt1.Should().NotBe(jwt2);
        }
Esempio n. 29
0
        public void ShouldBeSameJwtWhenDeterministicToken(string algorithm)
        {
            IdentityModelEventSource.ShowPII = true;
            var signingCredentials = new SigningCredentials(new CryptographicKey(algorithm), algorithm);
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt1 = handler.CreateToken(descriptor);
            var jwt2 = handler.CreateToken(descriptor);

            jwt1.Should().Be(jwt2);
        }
Esempio n. 30
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);
        }