public AuthenticationResult Execute(DTOUserCredentials userCredentials) { var existingUser = _userRepository.GetByEmail(userCredentials.Email, includes: new List <string> { nameof(User.Permission) }); if (existingUser != null) { var correctPassword = _encryption.CheckPassword(userCredentials.Password, existingUser.Password); if (correctPassword) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_config.JwtSecretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, existingUser.Id.ToString()), new Claim(ClaimTypes.Name, existingUser.Name), new Claim(ClaimTypes.Role, existingUser.Permission.Name), }), Expires = DateTime.UtcNow.AddHours(3), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(new AuthenticationResult { User = existingUser, Token = tokenHandler.WriteToken(token), Permission = existingUser.Permission.Name }); } } return(default);
public IActionResult GetAuthentication([FromBody] DTOUserCredentials body) { try { var validator = new UserAuthenticationValidation(); var rusultValidation = validator.Validate(body); if (!rusultValidation.IsValid) { return(BadRequest(rusultValidation.Errors)); } var resultAuthentication = _authService.Execute(body); if (resultAuthentication != null) { var dto = _mapper.Map <DTOResultAuthentication>(resultAuthentication); return(Ok(dto)); } return(BadRequest("Email ou senha invalido tente novamente.")); } catch { return(StatusCode((int)HttpStatusCode.InternalServerError, ErroMessage)); } }