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 SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token), username = userForLogInDTO.username })); }
public async Task <IActionResult> Login([FromBody] UserForLogInDTO dto) { // throw new Exception("Computer says no!"); var userFromRepo = await _repo.Login(dto.Username.ToLower(), dto.Password); if (userFromRepo == null) { return(Unauthorized()); } //generate token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.Username) }), Expires = DateTime.Now.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { tokenString })); }