private string GenerateJwtToken(string userId, string username) { // Function handles create the JWT token based on the provided // user ID and username // Generate the user claims by User Id & Name Claim[] jwtClaims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, username) }; // Generate the Key, using the App token SymmetricSecurityKey jwtKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); // Generate the creds SigningCredentials credentials = new SigningCredentials(jwtKey, SecurityAlgorithms.HmacSha512Signature); // Create a JWT Desc object SecurityTokenDescriptor jwtDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(jwtClaims), Expires = DateTime.Now.AddDays(1), SigningCredentials = credentials }; System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler jwtHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); // Finally create the JWT token & return it SecurityToken jwtToken = jwtHandler.CreateToken(jwtDescriptor); return(jwtHandler.WriteToken(jwtToken)); }
public static string Gen(string username) { var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); ConfigurationTocken ctkn = new ConfigurationTocken(); var key = System.Text.Encoding.ASCII.GetBytes(ctkn.SecretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, username) }), Expires = DateTime.UtcNow.AddMinutes(ctkn.timeExpire), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); //var userClaims = await _userManager.GetRolesAsync(user); List <Claim> claims = new List <Claim>(); claims.Add(new Claim(JwtRegisteredClaimNames.Sub, username)); claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)); var jwt = new JwtSecurityToken( claims: claims); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
private string GenerateJwtToken(User user) { var tokenhandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var keys = System.Text.Encoding.ASCII.GetBytes(jwtKey); var tokendescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }), Expires = DateTime.UtcNow.AddHours(24), SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keys), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature) }; var tokens = tokenhandler.CreateToken(tokendescriptor); return(tokenhandler.WriteToken(tokens)); }
public string GenerateJwtToken(User user) { var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("[SECRET USED TO SIGN AND VERIFY JWT TOKENS, IT CAN BE ANY STRING]"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new List <Claim>() { new Claim(nameof(User.Id).ToLowerInvariant(), user.Id.ToString()), new Claim(nameof(User.Name).ToLowerInvariant(), user.Name) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public Employee Authenticate(string username, string password)//User { var employee = _unitOfWork.EmployeeRepository.GetAll().SingleOrDefault(x => x.UserName == username && DecodePasswordFrom64(x.Password) == password); // return null if user not found if (employee == null) { return(null); } var employeeRoleIds = employee.EmployeeRoles.Select(r => (long)r.RoleId).ToList(); var roles = _unitOfWork.RoleRepository.GetRoles(employeeRoleIds.ToArray());//.Where(r => userRoleIds.Contains(r.Id)); var role = employee.EmployeeRoles.FirstOrDefault().Roles; // authentication successful so generate jwt token var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.JWT_Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, employee.Id.ToString()), new Claim(ClaimTypes.Role, role.Id.ToString()) }), //Expires = DateTime.UtcNow.AddDays(7), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenToBeSent = tokenHandler.WriteToken(token); //user.Token = tokenHandler.WriteToken(token); // remove password before returning //user.Password = null; employee.Token = tokenToBeSent.ToString(); employee.Password = null; return(employee); //return tokenToBeSent; }
static string GetJwtFromTokenIssuer() { byte[] key = Convert.FromBase64String("80ssGCKB931r2r8Lm3om1SIt5YY05yBZ34pna3+dYi8="); var symmetricKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key); //var symmetricKey = new InMemorySymmetricSecurityKey(key); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny") }); var descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor { Subject = claimsIdentity, Audience = "http://localhost:5000/api", Issuer = "http://authzserver.demo", Expires = DateTime.UtcNow.AddMinutes(1), SigningCredentials = signingCredentials }; //var descriptor = new SecurityTokenDescriptor() //{ // TokenIssuerName = "http://authzserver.demo", // AppliesToAddress = "http://localhost:5000/api", // Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(1)), // SigningCredentials = signingCredentials, // Subject = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[] // { // new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny") // }) //}; var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(descriptor); return(tokenHandler.WriteToken(token)); }
private void CreateToken() { var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var apiSecret = "adMvFxlEqySjPJQnzcTWm4I97oQz65khAlji"; byte[] symmetricKey = System.Text.Encoding.ASCII.GetBytes(apiSecret); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = "*****@*****.**", Expires = now.AddSeconds(3600), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.RsaSha256), }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); }
public async Task <IActionResult> Login(UserForLoginDto userForLoginDto) { var userFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password); if (userFromRepo == null) { return(Unauthorized()); } var claims = new [] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.UserName) }; var key = new tok.SymmetricSecurityKey(Encoding.UTF8. GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new tok.SigningCredentials(key, tok.SecurityAlgorithms.HmacSha256Signature); var tokenDescriptor = new tok.SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new jwt.JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var user = _mapper.Map <UserForListDto>(userFromRepo); return(Ok(new { token = tokenHandler.WriteToken(token), user })); }
/// <summary> /// Authenticate a user. /// </summary> /// <param name="dto"></param> /// <returns></returns> public TokenGetDto Authenticate(UserAuthenticationGetDto dto) { TokenGetDto tokenDto = new TokenGetDto(); User u = _userRepo.GetUser(dto.Mail); if (!u.Password.Equals(dto.Password, StringComparison.OrdinalIgnoreCase)) { throw new IncorrectPasswordException(); } var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("email", u.Mail), new Claim("userId", u.Id.ToString()), new Claim("personId", u.PersonId.ToString()) }), Expires = now.AddMinutes(2000), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.JwtToken.SecretKey)), SecurityAlgorithms.HmacSha256), }; var token = tokenHandler.CreateToken(tokenDescriptor); tokenDto = new TokenGetDto() { Token = tokenHandler.WriteToken(token), ValidTo = token.ValidTo }; return(tokenDto); }
public static bool TryIssueToken ( string issuer , string audience , string userName , IEnumerable <Claim> claims , out Microsoft .IdentityModel .Tokens .SecurityToken plainToken , out string secretTokenString , Microsoft .IdentityModel .Tokens .SymmetricSecurityKey signingKey , Microsoft .IdentityModel .Tokens .SigningCredentials signingCredentials //, IIdentity identity = null ) { bool r = false; plainToken = null; secretTokenString = null; try { IIdentity user = new JsonWebTokenUser ( userName , "jwt" , true ); var claimsIdentity = new ClaimsIdentity(user, claims); var securityTokenDescriptor = new Microsoft .IdentityModel .Tokens .SecurityTokenDescriptor() { Issuer = issuer, Audience = audience, IssuedAt = DateTime.Now, Subject = claimsIdentity, SigningCredentials = signingCredentials, }; var tokenHandler = new System .IdentityModel .Tokens .Jwt .JwtSecurityTokenHandler(); plainToken = tokenHandler.CreateToken(securityTokenDescriptor); secretTokenString = tokenHandler.WriteToken(plainToken); r = true; } catch (Exception e) { //throw; } return (r); }
public static bool TryIssueToken ( string issuer , string audience , IEnumerable <Claim> claims , out Microsoft.IdentityModel.Tokens.SecurityToken plainToken , out string secretTokenString , Microsoft .IdentityModel .Tokens .SymmetricSecurityKey signingKey , Microsoft .IdentityModel .Tokens .SigningCredentials signingCredentials ) { bool r = false; plainToken = null; secretTokenString = null; try { //var signingKey = new Microsoft // .IdentityModel // .Tokens // .SymmetricSecurityKey // ( // Encoding // .GetEncoding(plainTextSecurityKeyEncoding) // .GetBytes(plainTextSecurityKey) // ); //var signingCredentials // = new Microsoft.IdentityModel.Tokens.SigningCredentials // ( // signingKey // , signingCredentialsAlgorithm // , signingCredentialsDigest // ); // ComplexClaim var claimsIdentity = new ClaimsIdentity ( claims , "Custom" ); var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() { Issuer = issuer, Audience = audience, IssuedAt = DateTime.Now, Subject = claimsIdentity, SigningCredentials = signingCredentials, }; var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); plainToken = tokenHandler.CreateToken(securityTokenDescriptor); secretTokenString = tokenHandler.WriteToken(plainToken); r = true; } catch //(Exception) { //throw; } return (r); }