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 string GetJwt()
        {
            // Cria chave
            var key = Encoding.ASCII.GetBytes(Settings.Secret);

            // Cria token descriptor
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, "admin"),
                    new Claim("bookStore", "admin")
                }),
                Expires            = DateTime.UtcNow.AddHours(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            // Gera e retorna token
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #3
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);
        }
Пример #4
0
        public string GetJWT(int id, string role)
        {
            JwtSecurityTokenHandler tokenHanlder = new JwtSecurityTokenHandler();

            byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, id.ToString()),
                    new Claim(ClaimTypes.Role, role)
                }),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature
                    )
            };

            SecurityToken token = tokenHanlder.CreateToken(tokenDescriptor);

            return(tokenHanlder.WriteToken(token));
        }
Пример #5
0
        public async Task <string> GetJwt(string email)
        {
            var user = await GetUserAsync(email);

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserName.ToString()),
                    new Claim(ClaimTypes.Email, user.Email.ToString()),
                    new Claim(ClaimTypes.MobilePhone, user.MobileNumber)
                }),
                Issuer             = _appSettings.Issuer,
                Audience           = _appSettings.Audience,
                Expires            = DateTime.UtcNow.AddHours(_appSettings.Exp),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            return(tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)));
        }
Пример #6
0
        private object GenerateJwtToken(AppUser appUser)
        {
            var rep             = _unitOfWork.GetRepository <AppUser>();
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, appUser.UserName)
                    , new Claim(ClaimTypes.NameIdentifier, appUser.Id.ToString())
                }),
                //Expires = DateTime.UtcNow.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            appUser.Token = tokenHandler.WriteToken(token);
            rep.Update(appUser);
            rep.SaveChanges();

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        public string GenerateToken(string username)
        {
            var tokenInfo   = _appSettings.TokenOptions;
            var secretKey   = tokenInfo.SecretKey;
            var currentUser = _userRepository.SelectOne(x => x.UserName == username);
            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(secretKey);
            var tokenDescriptor = new SecurityTokenDescriptor {
                Issuer   = tokenInfo.Issuer,
                Audience = tokenInfo.Audience,
                Subject  = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.Name, Convert.ToString(currentUser.Id)),
                    new Claim("IsSuperAdmin", Convert.ToString(currentUser.IsSuperAdmin))
                }),
                Expires            = DateTime.UtcNow.AddMinutes(tokenInfo.AccessTokenExpiration),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var    token       = tokenHandler.CreateToken(tokenDescriptor);
            string tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Пример #8
0
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.GivenName, user.DisplayName)
            };

            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds,
                Issuer             = _config["Token:Issuer"]
            };

            var tokenHanlder = new JwtSecurityTokenHandler();

            var token = tokenHanlder.CreateToken(tokenDescriptor);

            return(tokenHanlder.WriteToken(token));
        }
Пример #9
0
 /// <summary>
 ///     Utwórz token autoryzacji
 /// </summary>
 /// <returns>JwtTokenModel</returns>
 public JwtTokenModel GenerateJwtToken()
 {
     try
     {
         var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
         var key = Encoding.UTF8.GetBytes(Key);
         var securityTokenDescriptor = new SecurityTokenDescriptor
         {
             Subject            = new ClaimsIdentity(new[] { new Claim("UserName", UserName) }),
             Expires            = DateTime.UtcNow.AddSeconds(Expires),
             SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                         SecurityAlgorithms.HmacSha256Signature)
         };
         JwtSecurityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
         JwtStringToken   = jwtSecurityTokenHandler.WriteToken(JwtSecurityToken);
         return(this);
     }
     catch (Exception e)
     {
         log4net.Error(string.Format("{0}, {1}", e.Message, e.StackTrace), e);
         return(null);
     }
 }
Пример #10
0
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Email, user.Email),
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.config["TokenKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds
            };

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

            return(tokenHandler.WriteToken(token));
        }
        public string Authenticate(string aadhar, string password)
        {
            if (!users.PensionerDetails.Any(u => u.AadhaarNo == aadhar && u.Password == password))
            {
                return(null);
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(tokenKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, aadhar)
                }),
                Expires            = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #12
0
        private string BuildToken(Response <UserDTO> userDTO)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, userDTO.Data.UserID.ToString())
                }),
                Expires            = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                Issuer             = _appSettings.Issuer,
                Audience           = _appSettings.Audience
            };

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

            return(tokenString);
        }
Пример #13
0
        public string GenerateJwtToken(Client client)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Audience = typeof(Program).FullName,
                Subject  = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Email, client.Email),
                    new Claim(ClaimTypes.Name, client.Name),
                    new Claim(ClaimTypes.NameIdentifier, client.Id.ToString()),
                    new Claim(ClaimTypes.Role, client.Role.ToString()),
                }),
                Expires            = DateTime.UtcNow.AddMinutes(double.Parse(_expDate)),
                Issuer             = typeof(JwtSecurityService).FullName,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #14
0
        public async ValueTask <Models.User> Authenticate(string username, string password, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (await _userRepository.GetUserByUsernamePassword(username, password, cancellationToken) is Models.User user)
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.UserId.ToString()) }),
                    Expires            = DateTime.UtcNow.AddMinutes(30),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                user.Token    = tokenHandler.WriteToken(token);
                user.Password = null;

                return(user);
            }
            _logger.LogInformation($"Authentication failed for user '{username}' at {DateTime.Now}");
            throw new NotFoundException("Username or password is incorrect");
        }
Пример #15
0
        public static string GenerateToken(Customer customer)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Convert.FromBase64String(Secret);

            var claimsIdentity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.NameIdentifier, customer.Id.ToString()),
                new Claim("IsBlocked", customer.Blocked.ToString())
            });
            var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = claimsIdentity,
                Issuer             = Issuer,
                Audience           = Audience,
                Expires            = DateTime.Now.AddMinutes(15),
                SigningCredentials = signingCredentials,
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #16
0
        public string GenerateJWT(int userId, string secret)
        {
            //Create JWT token
            var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, userId.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Пример #17
0
        /// <summary>
        /// Creates a new JWT security token containing <see cref="Claim"/>s based on <paramref name="user"/>.
        /// </summary>
        /// <param name="user">User who is logging in.</param>
        /// <returns>The encoded token as <c>string</c>.</returns>
        public string CreateToken(User user)
        {
            // create claims based on user's basic data
            var claims = new Claim[] {
                new Claim(nameof(User.Id), user.Id.ToString()),
                new Claim(nameof(User.Username), user.Username),
                new Claim(ClaimTypes.Role, user.Role.Name),
                new Claim(nameof(user.RoleId), user.Role.Id.ToString())
            };

            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject            = new ClaimsIdentity(claims),
                Issuer             = BaseUri,
                Audience           = BaseUri,
                Expires            = DateTime.UtcNow.AddMonths(1),
                SigningCredentials = new SigningCredentials(GetSecurityKey(), SecurityAlgorithms.HmacSha256)
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #18
0
        public IActionResult TokenGiver(string userId, Device deviceRole)
        {
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_configuration["JWTKey"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userId.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info and authentication token

            var conf   = _configuration["JWTKey"];
            var result = deviceRole;

            return(Ok(tokenString));
        }
Пример #19
0
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.NameId, user.UserName)
            };

            //generate signin credentials
            //ovaj key ostaje na serveru i ne salje se klijentu !
            // var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super secret key"));
            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds
            };

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

            return(tokenHandler.WriteToken(token));
        }
Пример #20
0
        private string SerializeToken(SecurityTokenDescriptor tokenDescriptor)
        {
            // see if token is encrypted
            var           encryptedToken = tokenDescriptor.Token as EncryptedSecurityToken;
            SecurityToken token;

            if (encryptedToken != null)
            {
                // use inner token
                token = encryptedToken.Token;
            }
            else
            {
                // if not, use the token directly
                token = tokenDescriptor.Token;
            }

            var sb = new StringBuilder(128);

            FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            return(sb.ToString());
        }
Пример #21
0
        public string CreateRefreshToken(DomainUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(CustomTokenClaims.Id, user.Id),
                new Claim(CustomTokenClaims.TokenVersion, user.TokenVersion.ToString())
            };

            var credentials = new SigningCredentials(_refreshKey, SecurityAlgorithms.HmacSha512);

            var tokenDescriptior = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = credentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptior);

            return(tokenHandler.WriteToken(token));
        }
Пример #22
0
        private string generateJwtToken(Login user)
        {
            // generate token that is valid for 7 days
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(new[] { new Claim("id", user.id.ToString()) }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            try
            {
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return(tokenHandler.WriteToken(token));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return("");
        }
Пример #23
0
        public static string GenerateToken(UsuarioDto usuario, long expireMinutes = 20)
        {
            var symmetricKey    = Convert.FromBase64String(Secret);
            var tokenHandler    = new JwtSecurityTokenHandler();
            var now             = DateTime.UtcNow;
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("user", Newtonsoft.Json.JsonConvert.SerializeObject(usuario, Formatting.Indented, new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                    }))
                }),

                Expires            = now.AddMinutes(Convert.ToInt32(expireMinutes)),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
            };
            var stoken = tokenHandler.CreateToken(tokenDescriptor);
            var token  = tokenHandler.WriteToken(stoken);

            return(token);
        }
Пример #24
0
        public string CreateJWT(User user)
        {
            var secretKey = configuration.GetSection("AppSettings:Key").Value;
            var key       = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            var claims = new Claim[] {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddMinutes(10),
                SigningCredentials = signingCredentials
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        public string Authenticate(string emailId, string password)
        {
            if (!users.Registers.Any(u => u.EmailId == emailId && u.Password == password))
            {
                return(null);
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(tokenKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, emailId)
                }),
                Expires            = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #26
0
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.NameId, user.UserName)
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Parallel Universe 96*"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #27
0
        public static string GenerateToken(string username)
        {
            byte[] key = Convert.FromBase64String(Secret);
            //1. create a SymmetricSecurityKey object by using the HMACSHA256 secret
            SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);
            //2.create (new) descriptor object. This represents the main content of the JWT,
            //such as the claims, the expiration date and the signing information.

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, username)
                }),
                Expires            = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(securityKey,
                                                            SecurityAlgorithms.HmacSha256Signature)
            };
            //3.Then, the token is created and a string version of it is returned.
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            JwtSecurityToken        token   = handler.CreateJwtSecurityToken(descriptor);

            return(handler.WriteToken(token));
        }
Пример #28
0
        private static string CreateToken(string userName, string[] roles)
        {
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, userName)
            };

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var key             = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims.ToArray()),
                Expires            = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #29
0
        public string CreateToken(AppUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.NameId, user.UserName)
            };

            // generate signing credentails
            var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #30
0
        //POST : /api/user/Login
        public async Task <IActionResult> Login(LoginModel model)
        {
            var user = await _userService.GetUserByName(model.UserName);

            if (user != null && model.Password == user.Password)
            {
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserId", user.Id.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);
                return(Ok(new { token }));
            }

            return(BadRequest(new { message = "Username or password is incorrect." }));
        }
Пример #31
0
        public void ValidateToken_ThrowsSecurityTokenValidationException_WhenIssuerIsBlank()
        {
            // Arrange
            string   audience          = TestWebsiteUrls[0];
            string   issuer            = "";
            TimeSpan lifetime          = new TimeSpan(24, 0, 0);
            DateTime tokenCreationDate = DateTime.UtcNow;
            DateTime tokenExpiryDate   = tokenCreationDate + lifetime;

            SecurityTokenDescriptor tokenDescriptor = this.GetTestSecurityTokenDescriptor(tokenCreationDate, tokenExpiryDate, audience, issuer);

            tokenDescriptor.TokenIssuerName = string.Empty;

            JwtSecurityTokenHandler securityTokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken        token = securityTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;

            // Act
            SecurityTokenInvalidIssuerException ex = Assert.Throws <SecurityTokenInvalidIssuerException>(() =>
                                                                                                         AppServiceTokenHandler.ValidateToken(token.RawData, TestSecretKey, audience, issuer));

            // Assert
            Assert.Contains("IDX10211: Unable to validate issuer. The 'issuer' parameter is null or whitespace", ex.Message, StringComparison.Ordinal);
        }
Пример #32
0
        public static string GenerateToken(string username, int expireMinutes = 1200)
        {
            var symmetricKey = Convert.FromBase64String(Secret);
            var tokenHandler = new JwtSecurityTokenHandler();

            var now             = DateTime.UtcNow;
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, username)
                }),

                Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),

                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
            };

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

            return(token);
        }
		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, "*****@*****.**"),
                }, "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");
        }