public ActionResult MyToken()
        {
            var config = ConfigurationRepository.Configuration;
            var samlHandler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection()[config.DefaultTokenType];
            
            var descriptor = new SecurityTokenDescriptor
            {
                AppliesToAddress = "http://self",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(config.DefaultTokenLifetime)),
                SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate),
                TokenIssuerName = config.IssuerUri,
                Subject = new ClaimsIdentity(GetClaims())
            };

            var token = samlHandler.CreateToken(descriptor);

            var sb = new StringBuilder(1024);
            samlHandler.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            return new ContentResult
            {
                ContentType = "text/xml",
                Content = sb.ToString()
            };
        }
示例#2
1
        private async Task<string> SignInAsync(User user, bool twoFactor)
        {
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            DateTime? tokenExpiration = null;
            var userPrincipal = await CreateUserPrincipalAsync(user);
            if(twoFactor)
            {
                userPrincipal.Identities.First().AddClaim(new Claim(ClaimTypes.AuthenticationMethod, JwtIdentityOptions.TwoFactorAuthenticationMethod));
                if(JwtIdentityOptions.TwoFactorTokenLifetime.HasValue)
                {
                    tokenExpiration = DateTime.UtcNow.Add(JwtIdentityOptions.TwoFactorTokenLifetime.Value);
                }
            }
            else
            {
                userPrincipal.Identities.First().AddClaim(new Claim(ClaimTypes.AuthenticationMethod, JwtIdentityOptions.AuthenticationMethod));
                if(JwtIdentityOptions.TokenLifetime.HasValue)
                {
                    tokenExpiration = DateTime.UtcNow.Add(JwtIdentityOptions.TokenLifetime.Value);
                }
            }

            var descriptor = new SecurityTokenDescriptor
            {
                Issuer = JwtIdentityOptions.Issuer,
                SigningCredentials = JwtIdentityOptions.SigningCredentials,
                Audience = JwtIdentityOptions.Audience,
                Subject = userPrincipal.Identities.First(),
                Expires = tokenExpiration
            };

            var securityToken = handler.CreateToken(descriptor);

            return handler.WriteToken(securityToken);
        }
		private SecurityTokenDescriptor GetTokenOptions(ClaimsIdentity identity) {
			var tokenDescriptor = new SecurityTokenDescriptor();
			tokenDescriptor.Issuer = tokenAuthorizationOptions.Issuer;
			tokenDescriptor.Audience = tokenAuthorizationOptions.Audience;
			tokenDescriptor.SigningCredentials = tokenAuthorizationOptions.SigningCredentials;
			tokenDescriptor.Subject = identity;
			tokenDescriptor.Expires = DateTime.Now.AddDays(24);

			return tokenDescriptor;
		}
        public void HandlerCreateRoundtripSingleClaimTypes()
        {
            var signinKey = SymmetricKeyGenerator.Create(32);

            var identity = new ClaimsIdentity(new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "dominick"),
                    new Claim(ClaimTypes.Email, "[email protected]"),
                }, "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");
        }