public static string CreateTokenString(JwtSecurityToken token)
        {
            JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>();

            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(token);
        }
Esempio n. 2
0
        private static void Main(string[] args)
        {
            var key = Convert.FromBase64String(SymmetricKey);
            var credentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(key),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, "bhogg"),
                    new Claim(ClaimTypes.GivenName, "Boss"),
                    new Claim(ClaimTypes.Surname, "Hogg"),
                    new Claim(ClaimTypes.Role, "Manager"),
                    new Claim(ClaimTypes.Role, "SeniorWorker"),
                }),
                TokenIssuerName = "corp",
                AppliesToAddress = "http://www.example.com",
                SigningCredentials = credentials,
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddYears(10))
            };

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

            Console.WriteLine(tokenString);
            Debug.WriteLine(tokenString);

            Console.ReadLine();
        }
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = System.Configuration.ConfigurationManager.AppSettings["as:AudienceId"];

            string symmetricKeyAsBase64 = System.Configuration.ConfigurationManager.AppSettings["as:AudienceSecret"];

            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey = new HmacSigningCredentials(keyByteArray);

            var issued = data.Properties.IssuedUtc;

            var expires = data.Properties.ExpiresUtc;

            var token = new System.IdentityModel.Tokens.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            //this.Unprotect("eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTM4NCJ9.eyJuYW1laWQiOiIyZGMxZTRlMC0xNjdjLTQ4MWQtOTZjMC0zOGQzYmIxNzA5ZDgiLCJ1bmlxdWVfbmFtZSI6IlVzdWFyaW8iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL2FjY2Vzc2NvbnRyb2xzZXJ2aWNlLzIwMTAvMDcvY2xhaW1zL2lkZW50aXR5cHJvdmlkZXIiOiJBU1AuTkVUIElkZW50aXR5IiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiJiNWNiMGMxYi05OWI2LTQ1NmItOWRiMC0xODRiNjE0NzVjNDciLCJyb2xlIjoiVXNlciIsIk15VHlwZSI6IjQ1IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDg5IiwiYXVkIjoiVHdpY2VUYWxlbnQiLCJleHAiOjE0ODk4NTMwNzgsIm5iZiI6MTQ4OTc2NjY3OH0.wuj8cRpwjCr75eyLrPpgvwUk8l0cmR07Cxetm_Ei2_Ym6At32QteM22tqT2hSaph");
            return(jwt);
        }
Esempio n. 4
0
        //http://blog.asteropesystems.com/securing-web-api-requests-with-json-web-tokens/
        public string GetToken(string username, List<ActivityClaim> activityClaims)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var now = DateTime.UtcNow;
            var claims = new ClaimsIdentity(new[]
                {
                    new Claim( ClaimTypes.UserData, "IsValid", ClaimValueTypes.String ),
                    new Claim( ClaimTypes.Name, username, ClaimValueTypes.String )
                });
            claims.AddClaims(activityClaims.Select(c => new Claim(ClaimTypes.UserData, c.ToString(), ClaimValueTypes.String)));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claims,
                TokenIssuerName = "self",
                AppliesToAddress = "https://api.knowthyshelf.com",
                Lifetime = new Lifetime(now, now.AddYears(10)),
                SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TOKEN_SECURITY_KEY),
                  "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                  "http://www.w3.org/2001/04/xmlenc#sha256"),
            };

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

            return tokenString;
        }
        public string CreateAssertionToken()
        {
            var now = DateTime.Now.ToUniversalTime();

            var jwt = new JwtSecurityToken(_clientId,
                                           _audience,
                                           new List<Claim>()
                                           {
                                               new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
                                               new Claim(JwtClaimTypes.Subject, _clientId),
                                               new Claim(JwtClaimTypes.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64)
                                           },
                                           now,
                                           now.AddMinutes(1),
                                           new X509SigningCredentials(_certificate,
                                               SecurityAlgorithms.RsaSha256Signature,
                                               SecurityAlgorithms.Sha256Digest
                                            )
                        );

            if (_embedCertificate)
            {
                var rawCertificate = Convert.ToBase64String(_certificate.Export(X509ContentType.Cert));
                jwt.Header.Add(JwtHeaderParameterNames.X5c, new[] {rawCertificate});
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            return tokenHandler.WriteToken(jwt);
        }
        public string Post(Credential credential)
        {
            if (credential.username == "admin" && credential.password == "123")
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var securityKey = Authorization.GetBytes("anyoldrandomtext");
                var now = DateTime.UtcNow;
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                     new Claim( ClaimTypes.UserData,"IsValid", ClaimValueTypes.String, "(local)" )
                     }),
                    TokenIssuerName = "self",
                    AppliesToAddress = "https://www.mywebsite.com",
                    Lifetime = new Lifetime(now, now.AddMinutes(60)),
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(securityKey),
                      "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                      "http://www.w3.org/2001/04/xmlenc#sha256"),
                };

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

                return tokenString;
            }
            else
            {
                return string.Empty;
            }
        }
Esempio n. 7
0
        public LoginResult PostSignIn([FromBody] LoginCredential credentials)
        {
            var auth = new LoginResult() { Authenticated = false };

            var userRoles = QueryableDependencies.GetLoginUserRoles(credentials.UserName, credentials.Password);
            if (userRoles.Count > 0)
            //if (userRoles.Where(r => r == "CredentialSystem").Any())
            {
                auth.Authenticated = true;

                var allClaims = userRoles.Select(r => new Claim(ClaimTypes.Role, r.ToString())).ToList();
                allClaims.Add(new Claim(ClaimTypes.Name, credentials.UserName));
                allClaims.Add(new Claim(ClaimTypes.Role, userRoles[0].ToString()));

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(allClaims),

                    AppliesToAddress = ConfigurationManager.AppSettings["JwtAllowedAudience"],
                    TokenIssuerName = ConfigurationManager.AppSettings["JwtValidIssuer"],
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(JwtTokenValidationHandler.SymmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")
                };

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

                auth.Token = tokenString;
            }

            return auth;
        }
        /// <summary>
        /// Sets a JWT authorization header on the default request headers of an <see cref="HttpClient"/>.
        /// </summary>
        /// <param name="client">The client for which to set the authorization header.</param>
        /// <param name="signingCertificate">The signing certificate to sign the token.</param>
        /// <param name="appliesToAddress">The address for which the token is considered valid.</param>
        /// <param name="claims">The claims that define the user. Leave null for an anonymous user.</param>
        /// <param name="tokenIssuerName">Name of the token issuer. Defaults to "self".</param>
        /// <param name="tokenDuration">
        /// The token duration for which it's considered valid. Defaults to 2 hours.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="signingCertificate"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="appliesToAddress"/> is <see langword="null"/> or empty.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="tokenIssuerName"/> is <see langword="null"/> or empty.
        /// </exception>
        public static void SetJwtAuthorizationHeader(
            this HttpClient client,
            X509Certificate2 signingCertificate,
            string appliesToAddress,
            IEnumerable<Claim> claims = null,
            string tokenIssuerName = "self",
            TimeSpan? tokenDuration = null)
        {
            signingCertificate.AssertNotNull("signingCertificate");
            appliesToAddress.AssertNotNullOrWhitespace("appliesToAddress");
            tokenIssuerName.AssertNotNullOrWhitespace("tokenIssuerName");

            var now = DateTime.UtcNow;
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                TokenIssuerName = tokenIssuerName,
                AppliesToAddress = appliesToAddress,
                Lifetime = new Lifetime(now, now.Add(tokenDuration ?? TimeSpan.FromHours(2))),
                SigningCredentials = new X509SigningCredentials(signingCertificate)
            };

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString);
        }
        public JwtAuthenticationOwinMiddlewareTests()
        {
            var signingCredentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(Convert.FromBase64String(Key)),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var now = DateTime.UtcNow;

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new []
                        {
                            new Claim("sub", "Alice"),
                            new Claim("email", "*****@*****.**"), 
                        }),
                TokenIssuerName = Issuer,
                AppliesToAddress = Audience,
                Lifetime = new Lifetime(now, now.AddMinutes(LifetimeInMinutes)),
                SigningCredentials = signingCredentials,
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            _tokenString = tokenHandler.WriteToken(token);
        }
Esempio n. 10
0
        public async Task<IHttpActionResult> CreateToken(Token token)
        {
            var publicAndPrivate = new RSACryptoServiceProvider();
            
            publicAndPrivate.FromXmlString(_configuration.PrivateKey.FromBase64String());
            var jwtToken = new JwtSecurityToken(
                                issuer: _configuration.Issuer, 
                                audience: "http://mysite.com"
                                , claims: new List<Claim>() { new Claim(ClaimTypes.Name, token.username) }
                                , notBefore: DateTime.UtcNow
                                , expires: DateTime.UtcNow.AddMinutes(1)
                                , signingCredentials: new SigningCredentials(
                                    new RsaSecurityKey(publicAndPrivate)
                                       ,SecurityAlgorithms.RsaSha256Signature
                                       ,SecurityAlgorithms.Sha256Digest)
                           );

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenString = tokenHandler.WriteToken(jwtToken);

            return Ok(new
            {
                access_token = tokenString,
                expires_in = new TimeSpan(0,0, 1,0).TotalSeconds,
                expires_on = (long)(DateTime.UtcNow.AddMinutes(1) - new DateTime(1970, 1, 1)).TotalSeconds
            });
        }
Esempio n. 11
0
        static string CreateTokenWithInMemorySymmetricSecurityKey()
        {
            var now = DateTime.UtcNow;
            var tokenHandler = new JwtSecurityTokenHandler();
            var symmetricKey = new RandomBufferGenerator(256 / 8).GenerateBufferFromSeed(256 / 8);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                        {
                            new Claim(ClaimTypes.Name, "Tugberk"),
                            new Claim(ClaimTypes.Role, "Sales"),
                        }),
                TokenIssuerName = "self",
                AppliesToAddress = "http://www.example.com",
                Lifetime = new Lifetime(now, now.AddMinutes(2)),
                SigningCredentials = new SigningCredentials(
                        new InMemorySymmetricSecurityKey(symmetricKey),
                        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                        "http://www.w3.org/2001/04/xmlenc#sha256")
            };

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
Esempio n. 12
0
        static string BearerToken()
        {
            var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";

            var securityKey = Convert.FromBase64String(mainKey);
            var inMemKey = new InMemorySymmetricSecurityKey(securityKey);

            ClaimsIdentity identity = new ClaimsIdentity();
            identity.AddClaim(new Claim("scope", "Full"));

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            SecurityToken securityToken = handler.CreateToken(new SecurityTokenDescriptor()
            {
                TokenType = "Bearer",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1)),
                SigningCredentials = new SigningCredentials(inMemKey, signatureAlgorithm, digestAlgorithm),
                //This data I would get by matching the jwtSecurityToken.Audience to database or something
                TokenIssuerName = "PaulsSite",
                AppliesToAddress = "http://JoshsSite",
                Subject = identity
            }
            );

            return handler.WriteToken(securityToken);
        }
Esempio n. 13
0
        public static string GetJwtToken(this ClaimsIdentity identity, SecurityTokenDescriptor tokenDescriptor)
        {
            if (identity == null || tokenDescriptor == null) return null;
            tokenDescriptor.Subject = identity;
            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
        public async Task<Client> FindClientByIdAsync(string clientId)
        {            
            var clientsUri = $"admin-api/api/clients/{clientId}";

            //var cert = Cert.Load(StoreName.My, StoreLocation.CurrentUser, "b512d01195667dbc7c4222ec6fd563ac64e3d450");
            //var handler = new WebRequestHandler();
            //handler.ClientCertificates.Add(cert);

            // Retrieve an access token from the IdentityAdmin /authorize OAuth endpoint
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.identityAdminUri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var cert = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test");

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("name", "idServer"),
                        new Claim("role", "IdentityAdminManager"),
                        new Claim("scope", "idadmin-api")
                    }),
                    TokenIssuerName = "idServer",                    
                    AppliesToAddress = this.identityAdminUri,
                    Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(10)),
                    SigningCredentials = new X509SigningCredentials(cert)
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var accessToken = tokenHandler.WriteToken(securityToken);

                var jwtParams = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role",
                    ValidAudience = this.identityAdminUri,
                    ValidIssuer = "idServer",                    
                    IssuerSigningToken = new X509SecurityToken(cert)                    
                };

                SecurityToken validatedToken;
                tokenHandler.ValidateToken(accessToken, jwtParams, out validatedToken);                

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                var response = await client.GetAsync(clientsUri);
                var str = await response.Content.ReadAsStringAsync();
            }

            return null;
        }
Esempio n. 15
0
#pragma warning disable 1998
        public override async Task<Result> Execute()
        {
            Result result = new Result();
            try
            {
                Console.Out.WriteLine("Generating access token...");

                // encryption key
                string key_s = ConfigurationManager.ConnectionStrings["JWTKey"].ConnectionString;
                byte[] key_b = new byte[key_s.Length * sizeof(char)];
                System.Buffer.BlockCopy(key_s.ToCharArray(), 0, key_b, 0, key_b.Length);

                // create the token
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                ClaimsIdentity subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Uri, SiteUrl, ClaimValueTypes.String) });
                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = subject,
                    TokenIssuerName = "SpSat",
                    Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(4)),
                    SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key_b), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")
                };
                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

                using (ClientContext context = new ClientContext(SiteUrl))
                {

                    // authenticate
                    string usernamePassword = ConfigurationManager.ConnectionStrings["SharePoint"].ConnectionString;
                    dynamic usernamePassword_j = Newtonsoft.Json.JsonConvert.DeserializeObject(usernamePassword);
                    string username = usernamePassword_j.username;
                    string password = usernamePassword_j.password;
                    SecureString password_s = new SecureString();
                    Array.ForEach(password.ToCharArray(), password_s.AppendChar);
                    context.Credentials = new SharePointOnlineCredentials(username, password_s);

                    // write the token to the property bag
                    PropertyValues webProperties = context.Web.AllProperties;
                    webProperties["accessToken"] = tokenHandler.WriteToken(token);
                    context.Web.Update();
                    context.ExecuteQuery();

                }

                Console.Out.WriteLine("Completed generating access token.");
                result.Status = Status.Success;
            }
            catch (Exception ex)
            {
                result.Status = Status.Failure;
                result.Log.Add(ex.Message);
            }
            return result;
        }
        public static string CreateTokenAsBase64(this SecurityTokenDescriptor securityTokenDescriptor)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            SecurityToken securityToken = tokenHandler.CreateToken(securityTokenDescriptor);
            string token = tokenHandler.WriteToken(securityToken);

            string tokenAsBase64 = token;

            return tokenAsBase64;
        }
        protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials)
        {
            var jwt = new JwtSecurityToken(
                token.Issuer,
                token.Audience,
                token.Claims,
                new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(token.Lifetime)),
                credentials);

            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(jwt);
        }
Esempio n. 18
0
        public static string GenerateToken(this ClaimsIdentity identity, string audienceId, string symmetricKeyAsBase64, string issuer, DateTimeOffset? issued, DateTimeOffset? expires)
        {
            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey = new HmacSigningCredentials(keyByteArray);

            var token = new JwtSecurityToken(issuer, audienceId, identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new JwtSecurityTokenHandler();

            string jwt = handler.WriteToken(token);
            return jwt;
        }
Esempio n. 19
0
        public static string CreateJwtToken(string userName, string role)
        {
            var claimList = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, userName),
                    new Claim(ClaimTypes.Role, role)     //Not sure what this is for
                };

            var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
            var sSKey = new InMemorySymmetricSecurityKey(SecurityConstants.KeyForHmacSha256);

            var jwtToken = tokenHandler.CreateToken(makeSecurityTokenDescriptor(sSKey, claimList));
            return tokenHandler.WriteToken(jwtToken);
        }
Esempio n. 20
0
        public void Can_create_and_consume_jwt_tokens()
        {
            const string issuer = "http://issuer.webapibook.net";
            const string audience = "*****@*****.**";
            const int lifetimeInMinutes = 5;

            var tokenHandler = new JwtSecurityTokenHandler();

            var symmetricKey = GetRandomBytes(256 / 8);
            var signingCredentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(symmetricKey),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var now = DateTime.UtcNow;

            var claims = new[]
            {
                new Claim("sub", "*****@*****.**"),
                new Claim("email", "*****@*****.**"),
                new Claim("name", "Alice"),
            };

            var token = new JwtSecurityToken(issuer, audience, claims,
                new Lifetime(now, now.AddMinutes(lifetimeInMinutes)), signingCredentials);

            var tokenString = tokenHandler.WriteToken(token);

            var parts = tokenString.Split('.');
            Assert.Equal(3, parts.Length);

            var validationParameters = new TokenValidationParameters()
            {
                AllowedAudience = audience,
                SigningToken = new BinarySecretSecurityToken(symmetricKey),
                ValidIssuer = issuer,
            };

            tokenHandler.NameClaimType = ClaimTypes.NameIdentifier;
            var principal = tokenHandler.ValidateToken(tokenString, validationParameters);

            var identity = principal.Identities.First();

            Assert.Equal("*****@*****.**", identity.Name);
            Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value);
            Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.Email).Value);
            Assert.Equal("Alice", identity.Claims.First(c => c.Type == "name").Value);
            Assert.Equal(issuer, identity.Claims.First().Issuer);
        }
 public static Token CreateToken(UserInfo user, string perms)
 {
     var claims = new List<Claim>()
         {
             new Claim(ClaimTypes.UserData, user.UserId.ToString()),
             new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()),
             new Claim(ClaimTypes.Sid, user.UserId.ToString()),
             new Claim(ClaimTypes.Name, user.FullName.ToString())
         };
     var key = new InMemorySymmetricSecurityKey(TokenConstants.TokenKey);
     var jwt = new JwtSecurityTokenHandler() { TokenLifetimeInMinutes = TokenConstants.TokenLifetimeInMinutes };
     var token = jwt.CreateToken(CreateSecurityTokenDescriptor(claims, key));
    
     return new Token() { Value = jwt.WriteToken(token), Expiry = TokenConstants.TokenLifetimeInMinutes, User = user.FullName, Perms = perms };
 }
 private string GetJwtString(string email, string firstName, string lastName)
 {
     var jwtTokenHandler = new JwtSecurityTokenHandler();
     var token = jwtTokenHandler.CreateToken(new SecurityTokenDescriptor
     {
         Subject = new ClaimsIdentity(new[]
         {
             new Claim(Authentication.ClaimTypes.Name, email),
             new Claim(Authentication.ClaimTypes.Email, email),
             new Claim(Authentication.ClaimTypes.Name, $"{firstName} {lastName}"),
             new Claim(Authentication.ClaimTypes.GivenName, firstName)
         }),
     });
     return jwtTokenHandler.WriteToken(token);
 }
		public async Task<IActionResult> Post([FromBody] RegistrationRequestModel registrationRequestModel)
		{
			if (!ModelState.IsValid)
			{
				return HttpUnauthorized();
			}
			
			if (UserManager.Users.Any(u => u.UserName == registrationRequestModel.UserName))
			{
				return HttpBadRequest($"User {registrationRequestModel.UserName} is already exists");
				// throw new DuplicateNameException();
			}

			var result = await UserManager.CreateAsync(new User()
			{
				UserName = registrationRequestModel.UserName,
				Email = registrationRequestModel.Email
			}, registrationRequestModel.Password);

			if (!result.Succeeded)
			{
				//TODO: change to aprop error
				return HttpUnauthorized();
			}

			var user = UserManager.Users.First(u => u.UserName == registrationRequestModel.UserName);

			var roles = await UserManager.GetRolesAsync(user);
			var claims = new List<Claim>(new Claim[] { new Claim(ClaimTypes.Name, user.UserName) });
			claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
			claims.AddRange(user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)));
			var identity = new ClaimsIdentity(claims, "JWT");

			var handler = new JwtSecurityTokenHandler();
			var rsa = new RSACryptoServiceProvider(2048);
			var rsaParams = rsa.ExportParameters(true);
			var rsaKey = new RsaSecurityKey(rsaParams);

			var secKey = string.Empty;   // Shared secure key that used for JWT auth

			var secToken = handler.CreateToken("myself", "myself", identity, DateTime.UtcNow, DateTime.UtcNow.AddDays(1),
				new SigningCredentials(rsaKey, JwtAlgorithms.RSA_SHA256, JwtAlgorithms.RSA_SHA256, secKey));


			var token = handler.WriteToken(secToken);

			return this.Ok(token);
		}
Esempio n. 24
0
        internal static string CreteJWTToken()
        {
            var cert = new X509SigningCredentials(SecurityHelper.GetCertificate());
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "Hulk"),
                new Claim(ClaimTypes.Spn, "superhero"),
                new Claim(ClaimTypes.Thumbprint, cert.Certificate.GetCertHashString()),
            };

            var token = new JwtSecurityToken(SecurityHelper.CertificateValidIssuer, SecurityHelper.CertificateValidAudience, claims, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(10), cert);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenData = tokenHandler.WriteToken(token);

            return tokenData;
        }
Esempio n. 25
0
        public static Wrapper Sign(List<Claim> claims, DateTime expiresIn, SigningCredentials credentials, string issuer, string audience)
        {
            /*
            System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();
            byte[] data = new byte[64];
            rng.GetBytes(data);
            BitConverter.ToString(data).Replace("-", "");
            */

            var notBefore = DateTime.Now;       //Not Before Date Expires
            var token = new JwtSecurityToken(issuer, audience, claims, notBefore, expiresIn, credentials);
            var handler = new JwtSecurityTokenHandler();
            var jwt = handler.WriteToken(token);

            return new Wrapper(expiresIn, "Bearer", jwt);
        }
Esempio n. 26
0
        /// <summary>
        ///     Generate an token.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns></returns>
        public string Generate(string username)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var now = DateTime.UtcNow;
            //The contents of the JWT token
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }),
                TokenIssuerName = JwtTokenGenerator.TokenIssuer,
                Lifetime = new Lifetime(now, now.AddHours(JwtTokenGenerator.LifetimeInHours)),
                SigningCredentials = this.credentials
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);
        }
        public Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters)
        {
            return Task.Run(() =>
            {
                tokenDescriptor.SigningCredentials = new X509SigningCredentials(this.cert);

                var tokenHandler = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var accessToken = tokenHandler.WriteToken(securityToken);

                validationParameters.IssuerSigningToken = new X509SecurityToken(this.cert);

                SecurityToken validatedToken;
                tokenHandler.ValidateToken(accessToken, validationParameters, out validatedToken);

                return accessToken;
            });
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            var securityKey = GetBytes("ThisIsAnImportantStringAndIHaveNoIdeaIfThisIsVerySecureOrNot!");

            var tokenHandler = new JwtSecurityTokenHandler();

            // Token Creation
            var now = DateTime.UtcNow;
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                        {
                            new Claim(ClaimTypes.Name, "Pedro"),
                            new Claim(ClaimTypes.Role, "Author"), 
                        }),
                TokenIssuerName = "self",
                AppliesToAddress = "http://www.example.com",
                Lifetime = new Lifetime(now, now.AddMinutes(2)),
                SigningCredentials = new SigningCredentials(
                    new InMemorySymmetricSecurityKey(securityKey),
                    "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                    "http://www.w3.org/2001/04/xmlenc#sha256"),
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            // Generate Token and return string
            var tokenString = tokenHandler.WriteToken(token);
            Console.WriteLine(tokenString);
            
            // Token Validation
            var validationParameters = new TokenValidationParameters()
            {
                AllowedAudience = "http://www.example.com",
                SigningToken = new BinarySecretSecurityToken(securityKey),
                ValidIssuer = "self"
            };

            // from Token to ClaimsPrincipal - easy!
            var principal = tokenHandler.ValidateToken(tokenString, validationParameters);

            Console.WriteLine(principal.Claims.Single(x => x.Type == ClaimTypes.Name).Value);

            Console.ReadLine();
        }
        /// <summary>
        /// Creates the json web token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials)
        {
            var jwt = new JwtSecurityToken(
                token.Issuer,
                token.Audience,
                token.Claims,
                DateTimeHelper.UtcNow,
                DateTimeHelper.UtcNow.AddSeconds(token.Lifetime),
                credentials);

            var x509credential = credentials as X509SigningCredentials;
            if (x509credential != null)
            {
                jwt.Header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash()));
            }

            var handler = new JwtSecurityTokenHandler();
            return handler.WriteToken(jwt);
        }
		/// <summary>
		/// The issue token.
		/// </summary>
		/// <returns>
		/// The <see cref="string"/>.
		/// </returns>
		private static string IssueToken()
		{
			JwtSecurityToken jwt = new JwtSecurityToken(
				issuer: "Dummy Cloud STS",
				audience: "http://aperture.identity/connectors",
				claims: new[]
							{
								// TODO: Add your claims here.
								new Claim("sub", "*****@*****.**")
							},
				notBefore: DateTime.UtcNow,
				expires: DateTime.UtcNow.AddHours(1),
				signingCredentials: new X509SigningCredentials(Certificate.ReadCertificate())
				// signingCredentials: new HmacSigningCredentials(GetIssuerKey())
			);
			JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();

			return jwtHandler.WriteToken(jwt);
		}
Esempio n. 31
-1
        private string CreateJwt(string userId, string role)
        {
            var key = Convert.FromBase64String(SymmetricKey);
            var credentials = new SigningCredentials(
                new InMemorySymmetricSecurityKey(key),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var expiration = DateTime.UtcNow.AddMinutes(20).ToLongTimeString();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, userId),
                    new Claim(ClaimTypes.Role, role),
                    new Claim("exp", expiration)
                }),
                TokenIssuerName = Issuer,
                AppliesToAddress = Audience,
                SigningCredentials = credentials
            };

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

            return tokenString;
        }