public IActionResult Refresh(TokenApiModel tokenApiModel) { if (tokenApiModel is null) { return(BadRequest("Invalid client request")); } string accessToken = tokenApiModel.AccessToken; string refreshToken = tokenApiModel.RefreshToken; var principal = tokenService.GetPrincipalFromExpiredToken(accessToken); var username = principal.Identity.Name; //this is mapped to the Name claim by default var user = sirhContext.User.SingleOrDefault(u => u.Email == username); if (user == null || user.RefreshToken != refreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { return(BadRequest("Invalid client request")); } var newAccessToken = tokenService.GenerateAccessToken(principal.Claims); var newRefreshToken = tokenService.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; sirhContext.SaveChanges(); return(new ObjectResult(new { accessToken = newAccessToken, refreshToken = newRefreshToken })); }
public IActionResult Login([FromBody] User loginModel) { if (loginModel == null) { return(BadRequest("Invalid client request")); } var user = sirhContext.User .FirstOrDefault(u => (u.Email == loginModel.Email) && (u.Password == loginModel.Password)); if (user == null) { return(Unauthorized()); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, loginModel.Email), }; var accessToken = tokenService.GenerateAccessToken(claims); var refreshToken = tokenService.GenerateRefreshToken(); user.RefreshToken = refreshToken; user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); sirhContext.SaveChanges(); return(Ok(user)); }