public void ManualWriteNoSig()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.None
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 500000,

                Claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**")
                }
            };

            var handler = new JsonWebTokenHandler();

            var token = handler.WriteToken(jwt);
            
            Trace.WriteLine(token);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(token));

            var parts = token.Split('.');
            Assert.IsTrue(parts.Length == 2, "JWT should have excactly 2 parts");
        }
        private void CreateTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var principal = Principal.Create("InMemory",
                new Claim(ClaimTypes.Name, UserName.Text));
            var tokenType = GetTokenType();
            
            var sts = new STS();
            SecurityToken token;

            var success = sts.TryIssueToken(
                new EndpointReference(Realm.Text),
                principal,
                tokenType,
                out token);

            if (success)
            {
                if (tokenType == TokenTypes.Saml2TokenProfile11 || tokenType == TokenTypes.Saml11TokenProfile11)
                {
                    var xml = token.ToTokenXmlString();
                    Output.Text = XElement.Parse(xml).ToString();
                }
                if (tokenType == TokenTypes.JsonWebToken)
                {
                    var tokenString = new JsonWebTokenHandler().WriteToken(token);
                    Output.Text = tokenString;
                }
            }
            else
            {
                throw new Exception("Error");
            }
        }
        public void ValidUserNameCredentialWithTokenValidation()
        {
            var client = new OAuth2Client(new Uri(baseAddress));

            var response = client.RequestAccessTokenUserName(
                Constants.Credentials.ValidUserName,
                Constants.Credentials.ValidPassword,
                scope);

            Assert.IsTrue(response != null, "response is null");
            Assert.IsTrue(!string.IsNullOrWhiteSpace(response.AccessToken), "access token is null");
            Assert.IsTrue(!string.IsNullOrWhiteSpace(response.TokenType), "token type is null");
            Assert.IsTrue(response.ExpiresIn > 0, "expiresIn is 0");

            Trace.WriteLine(response.AccessToken);

            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("http://identityserver45.thinktecture.com/trust/changethis", "http://identityserver45.thinktecture.com/trust/initial");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("http://identityserver45.thinktecture.com/trust/changethis", "3ihK5qGVhp8ptIk9+TDucXQW4Aaengg3d5m6gU8nzc8=");
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(scope));

            var handler = new JsonWebTokenHandler();
            handler.Configuration = config;

            var jwt = handler.ReadToken(response.AccessToken);

            var id = handler.ValidateToken(jwt);
        }
        private static string CreateJsonWebToken()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials(Constants.IdSrvSymmetricSigningKey)
                },

                Issuer = "http://selfissued.test",
                Audience = new Uri(Constants.Realm),

                Claims = new List<Sys.Claim>
                {
                    new Sys.Claim(Sys.ClaimTypes.Name, "bob"),
                    new Sys.Claim(Sys.ClaimTypes.Email, "*****@*****.**")
                }
            };

            var handler = new JsonWebTokenHandler();
            return handler.WriteToken(jwt);
        }
        public void ManualWriteHmacSha256MissingSigningCredentials()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 500000,

                Claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**")
                }
            };

            var handler = new JsonWebTokenHandler();

            var token = handler.WriteToken(jwt);
        }
        public void ManualWriteHmacSha256ValidSigningCredentials()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials(SymmetricKeyGenerator.Create(32))
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 500000,

                Claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**")
                }
            };

            var handler = new JsonWebTokenHandler();
            var token = handler.WriteToken(jwt);
            Trace.WriteLine(token);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(token));

            // token with signature needs to be 3 parts
            var parts = token.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");
        }
        public void ManualWriteUnsupportedSignatureAlgorithm()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = "unsupported",
                    SigningCredentials = new HmacSigningCredentials(SymmetricKeyGenerator.Create(48))
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 500000,

                Claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**")
                }
            };

            var handler = new JsonWebTokenHandler();
            var token = handler.WriteToken(jwt);
        }
Beispiel #8
0
        private static string CreateJwtToken(ClaimsPrincipal icp, int tokenExpiration)
        {
            var signingKey = ConfigurationManager.AppSettings["acsSigningKey"];

            var jwtHandler = new JsonWebTokenHandler();
            var securityDescriptor = new SecurityTokenDescriptor
            {
                Subject = icp.Identities.First(),
                SigningCredentials = new HmacSigningCredentials(signingKey),
                TokenIssuerName = ConfigurationManager.AppSettings["acsTokenIssuerName"],
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(tokenExpiration)),
                AppliesToAddress = ConfigurationManager.AppSettings["acsAppliesToAddress"]
            };

            var jwtToken = jwtHandler.CreateToken(securityDescriptor);
            var newTokenString = jwtHandler.WriteToken(jwtToken);

            return newTokenString;
        }
        public void ManualWriteRoundtripDuplicateClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials(signinKey)
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 50000000000,
            };

            jwt.AddClaim(ClaimTypes.Name, "dominick");
            jwt.AddClaim(ClaimTypes.Email, "*****@*****.**");
            jwt.AddClaim(ClaimTypes.Role, "bar");
            jwt.AddClaim(ClaimTypes.Role, "foo");


            var handler = new JsonWebTokenHandler();
            var token = handler.WriteToken(jwt);
            Trace.WriteLine(token);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(token));

            // token with signature needs to be 3 parts
            var parts = token.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");

            var jwtToken = handler.ReadToken(token);


            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("dominick", "dominick");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey));
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com"));

            handler.Configuration = config;
            var identity = handler.ValidateToken(jwtToken).First();

            Assert.IsTrue(identity.Claims.Count() == 4);
            Assert.IsTrue(identity.Claims.First().Issuer == "dominick");
        }
        public void ManualWriteHmacSha256KeySizeMismatch()
        {
            var jwt = new JsonWebToken
            {
                Header = new JwtHeader
                {
                    SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256,
                    SigningCredentials = new HmacSigningCredentials(SymmetricKeyGenerator.Create(48))
                },

                Audience = new Uri("http://foo.com"),
                Issuer = "dominick",
                ExpirationTime = 500000,

                Claims = new Dictionary<string, string>
                {
                    { ClaimTypes.Name, "dominick" },
                    { ClaimTypes.Email, "*****@*****.**" }
                }
            };

            var handler = new JsonWebTokenHandler();
            var token = handler.WriteToken(jwt);
        }
        public void HandlerCreateRoundtripSingleClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var identity = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "*****@*****.**"),
                }, "Custom");

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = identity,
                SigningCredentials = new HmacSigningCredentials(signinKey),
                TokenIssuerName = "dominick",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(8)),
                AppliesToAddress = "http://foo.com"
            };

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


            var tokenString = handler.WriteToken(token);
            Trace.WriteLine(tokenString);

            // token should not be empty
            Assert.IsTrue(!string.IsNullOrWhiteSpace(tokenString));

            // token with signature needs to be 3 parts
            var parts = tokenString.Split('.');
            Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts");

            // signature must be 256 bits
            var sig = Base64Url.Decode(parts[2]);
            Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits");

            var jwtToken = handler.ReadToken(tokenString);


            var config = new SecurityTokenHandlerConfiguration();
            var registry = new WebTokenIssuerNameRegistry();
            registry.AddTrustedIssuer("dominick", "dominick");
            config.IssuerNameRegistry = registry;

            var issuerResolver = new WebTokenIssuerTokenResolver();
            issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey));
            config.IssuerTokenResolver = issuerResolver;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com"));

            handler.Configuration = config;
            var identity2 = handler.ValidateToken(jwtToken).First();

            Assert.IsTrue(identity.Claims.Count() == 2);
            //Assert.IsTrue(identity.Claims.First().Issuer == "dominick");
        }