public async Task <IActionResult> Token(AuthorizeDTO authorize) { try { var response = await _tokenService.GetTokenAsync(authorize); return(Ok(response)); } catch (EntityNotExistException e) { return(StatusCode(401, e.Message)); } catch (IncorrectParamsException e) { return(StatusCode(401, e.Message)); } catch (DbUpdateConcurrencyException e) { return(StatusCode(403, e.Message)); } catch (Exception e) { return(BadRequest(e.Message)); } }
public IActionResult Authenticate([FromBody] AuthorizeDTO dto) { if (!ModelState.IsValid) { return(BadRequest()); } var loginUser = _service.Authenticate(dto.Username, Utility.HashPassword(dto.Password, _config)); if (loginUser == null) { return(Unauthorized()); } return(Ok(new { loginUser.Id, token = Utility.BuildToken(loginUser, _config, loginUser.Type) })); }
public async Task <TokenDTO> GetTokenAsync(AuthorizeDTO authorize) { authorize.Password = _hashMd5Service.GetMd5Hash(authorize.Password); var user = await(await _repository.GetAllAsync(t => t.Email.ToUpper().Equals(authorize.Email))).Include("UserRoles.Role").FirstOrDefaultAsync(); if (user == null) { throw new EntityNotExistException("Email address does not exist."); } var identity = GetIdentity(user); if (user.Password != authorize.Password || identity == null) { throw new IncorrectParamsException("Incorrect email or password."); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: _configuration["AuthOption:Issuer"], audience: _configuration["AuthOption:Audience"], notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(Convert.ToInt32(_configuration["AuthOption:Lifetime"]))), signingCredentials: new SigningCredentials( new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["AuthOption:Key"])), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new TokenDTO { AccessToken = encodedJwt, Username = identity.Name, Roles = user.UserRoles.Select(role => role.Role.Name).ToList() }; return(response); }