static void TokenDemo()
        {
            Saml2SecurityTokenHandler h = new Saml2SecurityTokenHandler();
            var token = h.CreateToken(new SecurityTokenDescriptor());

            System.Console.WriteLine(token);
        }
Beispiel #2
0
        static GenericXmlSecurityToken WrapJwt(string jwt)
        {
            var subject = new ClaimsIdentity("saml");

            subject.AddClaim(new Claim("jwt", jwt));

            var descriptor = new SecurityTokenDescriptor
            {
                TokenType       = TokenTypes.Saml2TokenProfile11,
                TokenIssuerName = "urn:wrappedjwt",
                Subject         = subject
            };

            var handler = new Saml2SecurityTokenHandler();
            var token   = handler.CreateToken(descriptor);

            var xmlToken = new GenericXmlSecurityToken(
                XElement.Parse(token.ToTokenXmlString()).ToXmlElement(),
                null,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                null,
                null,
                null);

            return(xmlToken);
        }
Beispiel #3
0
        public static Saml2SecurityToken CreateSaml2SecurityTokenSigningByRsa(byte[] certificate, string password, params Claim[] claims)
        {
            var descriptor = new SecurityTokenDescriptor();

            var digestAlgorithm    = "http://www.w3.org/2000/09/xmldsig#sha1";
            var signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            var signingCert = new X509Certificate2(certificate, password);

            var rsa                = signingCert.PrivateKey as RSACryptoServiceProvider;
            var rsaKey             = new RsaSecurityKey(rsa);
            var rsaClause          = new RsaKeyIdentifierClause(rsa);
            var signingSki         = new SecurityKeyIdentifier(rsaClause);
            var signingCredentials = new SigningCredentials(rsaKey, signatureAlgorithm, digestAlgorithm, signingSki);

            descriptor.TokenType          = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
            descriptor.TokenIssuerName    = "CN=app.nhin-hv.com, OU=Domain Control Validated, O=app.nhin-hv.com";
            descriptor.SigningCredentials = signingCredentials;
            descriptor.Subject            = new ClaimsIdentity(claims);
            descriptor.AppliesToAddress   = "http://localhost/RelyingPartyApplication";

            var issueInstant = DateTime.UtcNow;

            descriptor.Lifetime = new Lifetime(issueInstant, issueInstant + TimeSpan.FromHours(8));

            var tokenHandler = new Saml2SecurityTokenHandler();
            var token        = tokenHandler.CreateToken(descriptor) as Saml2SecurityToken;

            return(token);
        }
Beispiel #4
0
        public async Task <string> GenerateSerializedRstr(ValidatedWsFederationSigninRequest request)
        {
            var now = _clock.UtcNow.UtcDateTime;

            var principal   = request.Subject.Identity as ClaimsIdentity;
            var nameIdClaim = principal.FindFirst(ClaimTypes.NameIdentifier);

            if (nameIdClaim == null)
            {
                nameIdClaim = new Claim(ClaimTypes.NameIdentifier, principal.Name);
                nameIdClaim.Properties.Add(ClaimProperties.SamlNameIdentifierFormat, Saml2Constants.NameIdentifierFormats.UnspecifiedString);
                principal.AddClaim(nameIdClaim);
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = request.RequestMessage.Wtrealm,
                Expires            = now.AddSeconds(request.Client.IdentityTokenLifetime),
                IssuedAt           = now,
                Issuer             = _options.IssuerUri,
                NotBefore          = now,
                SigningCredentials = await _keys.GetSigningCredentialsAsync(),
                Subject            = principal
            };

            //For whatever reason, the Digest method isn't specified in the builder extensions for identity server.
            //Not a good solution to force the user to use th eoverload that takes SigningCredentials
            //IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs
            //Instead, it should be supported in:
            //  The overload that takes a X509Certificate2
            //  The overload that looks it up in a cert store
            //  The overload that takes an RsaSecurityKey
            //  AddDeveloperSigningCredential
            //For now, this is a workaround.
            if (tokenDescriptor.SigningCredentials.Digest == null)
            {
                _logger.LogInformation($"SigningCredentials does not have a digest specified. Using default digest algorithm of {SecurityAlgorithms.Sha256Digest}");
                tokenDescriptor.SigningCredentials = new SigningCredentials(tokenDescriptor.SigningCredentials.Key, tokenDescriptor.SigningCredentials.Algorithm, SecurityAlgorithms.Sha256Digest);
            }

            _logger.LogDebug("Creating SAML 2.0 security token.");
            var tokenHandler = new Saml2SecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            _logger.LogDebug("Serializing RSTR.");
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new AppliesTo(request.RequestMessage.Wtrealm),
                KeyType   = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey",
                Lifetime  = new Lifetime(now, now.AddSeconds(request.Client.IdentityTokenLifetime)),
                RequestedSecurityToken = token,
                RequestType            = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue",
                TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
            };

            return(RequestSecurityTokenResponseSerializer.Serialize(rstr));
        }
Beispiel #5
0
        private void CreateSaml2Tokens(SecurityTokenDescriptor tokenDescriptor)
        {
            Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler();
            Saml2SecurityToken        token            = samlTokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken;
            MemoryStream        ms     = new MemoryStream();
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms);

            samlTokenHandler.WriteToken(writer, token);
        }
        static async Task Main(string[] args)
        {
            IdentityModelEventSource.ShowPII = true;

            await Task.Delay(5000);

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name, "username")
            };
            var identity = new ClaimsIdentity(claims, "Sample");
            var handler  = new Saml2SecurityTokenHandler();

            var parameters = CreateRsaParameters();

            using var rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(parameters);

            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "urn:sample.identityprovider",
                Audience           = "urn:sample.issuer",
                IssuedAt           = DateTime.UtcNow,
                NotBefore          = DateTime.UtcNow.AddMinutes(-5),
                Expires            = DateTime.UtcNow.AddHours(2),
                Subject            = identity,
                SigningCredentials = SignatureMethod.RsaSha256.CreateCredentials(new RsaSecurityKey(rsa))
            };
            var token = handler.CreateToken(descriptor);

            var binding  = new WsTrustIssuedTokenBinding();
            var endpoint = new EndpointAddress("https://localhost:5001/trust/13");

            var factory = new WsTrustChannelFactory(binding, endpoint);

            factory.SecurityTokenHandlers.Add(handler);

            for (var i = 0; i < iterations; i++)
            {
                var channel = factory.CreateChannelWithIssuedToken(token);

                var request = new WsTrustRequest(WsTrustConstants.Trust13.WsTrustActions.Issue)
                {
                    KeyType   = WsTrustKeyTypes.Trust13.Bearer,
                    AppliesTo = new AppliesTo(new EndpointReference("urn:sample:relyingparty"))
                };
                var response = await channel.IssueAsync(request);

                var requestedToken = response.GetRequestedSecurityToken() as GenericXmlSecurityToken;

                var assertion = requestedToken.Element.OuterXml;
                Console.WriteLine(assertion);
            }
            Console.ReadKey();
        }
Beispiel #7
0
        public async Task <string> GenerateSerializedRstr(ValidatedWsFederationRequest request)
        {
            var now        = _clock.UtcNow.UtcDateTime;
            var credential = await _keys.GetSigningCredentialsAsync();

            var key = credential.Key as X509SecurityKey;

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = request.RequestMessage.Wtrealm,
                Expires            = now.AddSeconds(request.Client.IdentityTokenLifetime),
                IssuedAt           = now,
                Issuer             = _options.IssuerUri,
                NotBefore          = now,
                SigningCredentials = key == null ? credential : new X509SigningCredentials(key.Certificate, _federationOptions.DefaultSignatureAlgorithm),
                Subject            = await CreateSubjectAsync(request)
            };

            //For whatever reason, the Digest method isn't specified in the builder extensions for identity server.
            //Not a good solution to force the user to use the overload that takes SigningCredentials
            //IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs
            //Instead, it should be supported in:
            //  The overload that takes a X509Certificate2
            //  The overload that looks it up in a cert store
            //  The overload that takes an RsaSecurityKey
            //  AddDeveloperSigningCredential
            //For now, this is a workaround.
            if (tokenDescriptor.SigningCredentials.Digest == null)
            {
                _logger.LogInformation($"SigningCredentials does not have a digest specified. Using default digest algorithm of {SecurityAlgorithms.Sha256Digest}");
                tokenDescriptor.SigningCredentials = new SigningCredentials(tokenDescriptor.SigningCredentials.Key, tokenDescriptor.SigningCredentials.Algorithm ?? _federationOptions.DefaultSignatureAlgorithm, _federationOptions.DefaultDigestAlgorithm);
            }

            _logger.LogDebug("Creating SAML 2.0 security token.");

            var tokenHandler = new Saml2SecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            _logger.LogDebug("Serializing RSTR.");
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new AppliesTo(request.RequestMessage.Wtrealm),
                KeyType   = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey",
                Lifetime  = new Lifetime
                {
                    Created = XmlConvert.ToString(now, XmlDateTimeSerializationMode.Utc),
                    Expires = XmlConvert.ToString(now.AddSeconds(request.Client.IdentityTokenLifetime), XmlDateTimeSerializationMode.Utc),
                },
                RequestedSecurityToken = token,
                RequestType            = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue",
                TokenType = WsFederationConstants.TokenTypes.Saml2TokenProfile11
            };

            return(RequestSecurityTokenResponseSerializer.Serialize(rstr));
        }
Beispiel #8
0
        public MeasureTokenHandlers()
        {
            IdentityModelEventSource.ShowPII = true;
            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = TestData.Audience,
                Claims             = TestData.ClaimsDictionary,
                Issuer             = TestData.Issuer,
                Subject            = TestData.Subject,
                SigningCredentials = TestData.RsaSigningCredentials_2048Sha256
            };

            _jwtToken   = _jsonWebTokenHandler.CreateToken(securityTokenDescriptor);
            _saml1Token = _saml1SecurityTokenHandler.WriteToken(_saml1SecurityTokenHandler.CreateToken(securityTokenDescriptor));
            _saml2Token = _saml2SecurityTokenHandler.WriteToken(_saml2SecurityTokenHandler.CreateToken(securityTokenDescriptor));
            _tokenValidationParameters = TestData.RsaTokenValidationParameters_2048_Public;
        }
        public static string CreateSaml2Token(string name)
        {
            var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "SAML");

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = id,
                AppliesToAddress = "https://test",
                TokenIssuerName = "http://issuer",
                SigningCredentials = GetSamlSigningCredential(),
            };

            var handler = new Saml2SecurityTokenHandler();
            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var token = handler.CreateToken(descriptor);
            return token.ToTokenXmlString();
        }
Beispiel #10
0
        private static Saml2SecurityToken CreateSaml2Token(IList <Claim> claims)
        {
            var saml2TokenHandler = new Saml2SecurityTokenHandler();
            var tokenDescriptor   = new SecurityTokenDescriptor
            {
                Audience           = Default.Audience,
                NotBefore          = Default.NotBefore,
                Expires            = Default.Expires,
                IssuedAt           = Default.IssueInstant,
                Issuer             = Default.Issuer,
                SigningCredentials = Default.AsymmetricSigningCredentials,
                Subject            = new ClaimsIdentity(claims)
            };

            var token = saml2TokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken;

            token.SigningKey = Default.AsymmetricSigningKey;
            return(token);
        }
Beispiel #11
0
        private static SecurityToken GenerateHardcodedToken()
        {
            var securityTokenDescriptor = new SecurityTokenDescriptor();

            securityTokenDescriptor.Subject            = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
            securityTokenDescriptor.Lifetime           = new Lifetime(DateTime.Now, DateTime.Now.AddDays(2));
            securityTokenDescriptor.TokenIssuerName    = "http://identityserver.v2.thinktecture.com/trust/changethis";
            securityTokenDescriptor.AppliesToAddress   = "https://windows7:444/identity/wstrust/bearer";
            securityTokenDescriptor.SigningCredentials = GenerateSigningCredentials();

            Saml2SecurityTokenHandler saml2SecurityTokenHandler = new Saml2SecurityTokenHandler();
            var saml2SecurityToken = saml2SecurityTokenHandler.CreateToken(securityTokenDescriptor) as Saml2SecurityToken;

            var authenticationMethod  = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password";
            var authenticationContext = new Saml2AuthenticationContext(new Uri(authenticationMethod));

            saml2SecurityToken.Assertion.Statements.Add(new Saml2AuthenticationStatement(authenticationContext));

            return(saml2SecurityToken);
        }
        public static string CreateSaml2Token(string name)
        {
            var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "SAML");

            var descriptor = new SecurityTokenDescriptor
            {
                Subject            = id,
                AppliesToAddress   = "https://test",
                TokenIssuerName    = "http://issuer",
                SigningCredentials = GetSamlSigningCredential(),
            };

            var handler = new Saml2SecurityTokenHandler();

            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var token = handler.CreateToken(descriptor);

            return(token.ToTokenXmlString());
        }
Beispiel #13
0
        public ActionResult <string> Login()
        {
            var user = new User
            {
                Id          = 1,
                Name        = "jjj",
                Email       = "*****@*****.**",
                Birthday    = DateTime.Now.AddYears(-10),
                Password    = "******",
                PhoneNumber = "18888888888"
            };

            var tokenHandler   = new Saml2SecurityTokenHandler();
            var privateKey     = System.IO.File.ReadAllText(Path.Combine(_env.ContentRootPath, "private.key"));
            var rsaParameters  = JsonConvert.DeserializeObject <RSAParameters>(privateKey);
            var rsaSecurityKey = new RsaSecurityKey(rsaParameters);

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Issuer             = "https://www.jjj.me",
                Audience           = "https://api.jjj.me",
                NotBefore          = DateTime.Now,
                Expires            = DateTime.UtcNow.AddMinutes(15),
                SigningCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest),
                Subject            = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                    new Claim(ClaimTypes.Role, "Manager")
                })
            };

            var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

            return(token);
        }
Beispiel #14
0
        static string CreateSamlToken()
        {
            var user = new User
            {
                Id          = 1,
                Name        = "123",
                Email       = "*****@*****.**",
                Birthday    = DateTime.Now.AddYears(-27),
                PhoneNumber = "123456789"
            };
            var tokenHandler = new Saml2SecurityTokenHandler();

            string keyPrivate     = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "key.private.json"));
            var    keyParameter   = JsonConvert.DeserializeObject <RSAParameters>(keyPrivate);
            var    rsaSecurityKey = new RsaSecurityKey(keyParameter);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = "aspnetcoreweb",
                Issuer             = "xcode.me",
                NotBefore          = DateTime.Now,
                Expires            = DateTime.UtcNow.AddMinutes(6),
                SigningCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest),
                Subject            = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                    new Claim(ClaimTypes.Role, "Manager")
                })
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
            /// <summary>
            /// Creates a token for transaction service channel factory.
            /// </summary>
            /// <returns>Token for transaction service.</returns>
            private System.IdentityModel.Tokens.SecurityToken CreateToken()
            {
                ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                Claim          claim;

                claim = new Claim(ClaimTypes.Email, this.transactionServiceProfile.UserId);
                claimsIdentity.Claims.Add(claim);
                claim = new Claim(this.transactionServiceProfile.IdentityProviderClaim, this.transactionServiceProfile.IdentityProvider);
                claimsIdentity.Claims.Add(claim);
                claim = new Claim(ClaimTypes.NameIdentifier, this.transactionServiceProfile.UserId);
                claimsIdentity.Claims.Add(claim);
                Saml2SecurityTokenHandler tokenHandler = new Saml2SecurityTokenHandler();

                tokenHandler.SamlSecurityTokenRequirement = new SamlSecurityTokenRequirement();
                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor();

                tokenDescriptor.TokenType       = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11;
                tokenDescriptor.TokenIssuerName = this.transactionServiceProfile.IssuerUri;
                tokenDescriptor.Subject         = claimsIdentity;
                DateTime currentUtcTime = DateTime.UtcNow;

                tokenDescriptor.Lifetime         = new Microsoft.IdentityModel.Protocols.WSTrust.Lifetime(currentUtcTime, currentUtcTime.AddHours(24));
                tokenDescriptor.AppliesToAddress = this.transactionServiceProfile.AudienceUrn;
                X509Certificate2 signingCert = this.FindCertificate();

                if (signingCert != null)
                {
                    tokenDescriptor.SigningCredentials = new X509SigningCredentials(signingCert);
                }
                else
                {
                    throw new ArgumentException("Error locating certificate by thumbprint");
                }

                return(tokenHandler.CreateToken(tokenDescriptor));
            }
 public static Saml2SecurityToken CreateSaml2Token(SecurityTokenDescriptor securityTokenDescriptor, Saml2SecurityTokenHandler tokenHandler)
 {
     return(tokenHandler.CreateToken(securityTokenDescriptor) as Saml2SecurityToken);
 }
        public static void Run(string[] args)
        {
            IdentityModelEventSource.ShowPII = true;
            var testRuns = TestConfig.SetupTestRuns(
                new List <TestExecutor>
            {
                TokenTestExecutors.JsonWebTokenHandler_ValidateToken_InParallel,
                TokenTestExecutors.JwtSecurityTokenHandler_ValidateToken_InParallel,
                TokenTestExecutors.Saml2SecurityTokenHandler_ValidateToken_InParallel,
                TokenTestExecutors.SamlSecurityTokenHandler_ValidateToken_InParallel,
                TokenTestExecutors.JsonWebTokenHandler_CreateToken_InParallel,
                TokenTestExecutors.JwtSecurityTokenHandler_CreateToken_InParallel,
                TokenTestExecutors.Saml2SecurityTokenHandler_CreateToken_InParallel,
                TokenTestExecutors.SamlSecurityTokenHandler_CreateToken_InParallel,
            });

            var securityTokenDescriptor   = TestData.SecurityTokenDescriptor(TestData.RsaSigningCredentials_2048Sha256);
            var tokenValidationParameters = TestData.TokenValidationParameters(securityTokenDescriptor.SigningCredentials.Key);
            var jwtTokenHandler           = new JwtSecurityTokenHandler();
            var jwt = jwtTokenHandler.CreateEncodedJwt(securityTokenDescriptor);
            var samlTokenHandler  = new SamlSecurityTokenHandler();
            var samlToken         = samlTokenHandler.CreateToken(securityTokenDescriptor);
            var saml              = samlTokenHandler.WriteToken(samlToken);
            var saml2TokenHandler = new Saml2SecurityTokenHandler();
            var saml2Token        = saml2TokenHandler.CreateToken(securityTokenDescriptor);
            var saml2             = saml2TokenHandler.WriteToken(saml2Token);

            var testConfig    = TestConfig.ParseArgs(args);
            var tokenTestData = new TokenTestRunData
            {
                JwtSecurityTokenHandler = new JwtSecurityTokenHandler(),
                JsonWebTokenHandler     = new JsonWebTokenHandler(),
                JwtToken                  = jwt,
                NumIterations             = testConfig.NumIterations,
                Saml2Token                = saml2,
                SamlToken                 = saml,
                SamlSecurityTokenHandler  = samlTokenHandler,
                Saml2SecurityTokenHandler = saml2TokenHandler,
                TokenValidationParameters = tokenValidationParameters,
                SecurityTokenDescriptor   = securityTokenDescriptor
            };

            // run each test to set any static data
            foreach (var testRun in testRuns)
            {
                testRun.TestExecutor(tokenTestData);
            }

            var assemblyVersion = typeof(JwtSecurityTokenHandler).Assembly.GetName().Version.ToString();

#if DEBUG
            var prefix = "DEBUG";
#else
            var prefix = "RELEASE";
#endif
            testConfig.Version = $"{prefix}-{assemblyVersion}";
            var logName   = $"SecurityTokens-{testConfig.Version}_{DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss")}.txt";
            var directory = testConfig.LogDirectory;
            var logFile   = Path.Combine(directory, logName);
            Directory.CreateDirectory(directory);

            TestRunner.Run(testConfig, testRuns, tokenTestData);
            File.WriteAllText(logFile, testConfig.Logger.Logs);
        }
Beispiel #18
0
        private void RunValidationTests(SecurityTokenDescriptor tokenDescriptor, SecurityToken securityToken, SecurityKey key, int iterations, bool display = true)
        {
            // Create jwts using wif
            // Create Saml2 tokens
            // Create Saml tokens

            DateTime started;
            string   validating = "Validating, signed: '{0}', '{1}' Tokens. Time: '{2}'";

            SetReturnSecurityTokenResolver str = new Test.SetReturnSecurityTokenResolver(securityToken, key);

            SecurityTokenHandlerConfiguration tokenHandlerConfiguration = new SecurityTokenHandlerConfiguration()
            {
                IssuerTokenResolver  = str,
                SaveBootstrapContext = true,
                CertificateValidator = AlwaysSucceedCertificateValidator.New,
                AudienceRestriction  = new AudienceRestriction(AudienceUriMode.Never),
                IssuerNameRegistry   = new SetNameIssuerNameRegistry(Issuers.GotJwt),
            };

            Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler();
            Saml2SecurityToken        token            = samlTokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken;
            StringBuilder             sb = new StringBuilder();
            XmlWriter writer             = XmlWriter.Create(sb);

            samlTokenHandler.WriteToken(writer, token);
            writer.Flush();
            writer.Close();
            string tokenXml = sb.ToString();

            samlTokenHandler.Configuration = tokenHandlerConfiguration;
            started = DateTime.UtcNow;
            for (int i = 0; i < iterations; i++)
            {
                StringReader        sr     = new StringReader(tokenXml);
                XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr));
                reader.MoveToContent();
                SecurityToken saml2Token = samlTokenHandler.ReadToken(reader);
                samlTokenHandler.ValidateToken(saml2Token);
            }
            if (display)
            {
                Console.WriteLine(string.Format(validating, "Saml2SecurityTokenHandler", iterations, DateTime.UtcNow - started));
            }

            JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken        jwt             = jwtTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;

            jwtTokenHandler.Configuration = tokenHandlerConfiguration;
            started = DateTime.UtcNow;
            for (int i = 0; i < iterations; i++)
            {
                jwtTokenHandler.ValidateToken(jwt.RawData);
            }

            if (display)
            {
                Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ValidateToken( jwt.RawData )", iterations, DateTime.UtcNow - started));
            }

            jwt    = jwtTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
            sb     = new StringBuilder();
            writer = XmlWriter.Create(sb);
            jwtTokenHandler.WriteToken(writer, jwt);
            writer.Flush();
            writer.Close();
            tokenXml = sb.ToString();

            started = DateTime.UtcNow;
            for (int i = 0; i < iterations; i++)
            {
                StringReader        sr     = new StringReader(tokenXml);
                XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr));
                reader.MoveToContent();
                SecurityToken jwtToken = jwtTokenHandler.ReadToken(reader);
                jwtTokenHandler.ValidateToken(jwtToken);
            }

            if (display)
            {
                Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken )", iterations, DateTime.UtcNow - started));
            }

            started = DateTime.UtcNow;
            for (int i = 0; i < iterations; i++)
            {
                StringReader        sr     = new StringReader(tokenXml);
                XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr));
                reader.MoveToContent();
                JwtSecurityToken jwtToken = jwtTokenHandler.ReadToken(reader) as JwtSecurityToken;
                jwtTokenHandler.ValidateToken(jwtToken.RawData);
            }

            if (display)
            {
                Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken.RawData )", iterations, DateTime.UtcNow - started));
            }
        }