public IActionResult Login([FromBody] Authenticate userModel) { /// <summary>Method for verification if user with given email exists</summary> var user = _authService.Authenticate(userModel); if (user == null) { return(Unauthorized()); } /// <summary>CLAIMS and Tokens creation</summary> var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.FirstName), new Claim(ClaimTypes.Surname, user.LastName), new Claim(ClaimTypes.Role, user.Role), new Claim(ClaimTypes.Email, user.Email), }; var accessToken = _tokenService.GenerateAccessToken(claims); var refreshToken = _tokenService.GenerateRefreshToken(); user.RefreshToken = refreshToken; user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); /// <summary>Save changes to database</summary> _appDbContext.SaveChanges(); /// <summary>return tokens and CLAIMS</summary> return(Ok(new { Token = accessToken, RefreshToken = refreshToken, Claims = claims })); }
public IActionResult Refresh(Token tokenApiModel) { if (tokenApiModel.AccessToken == null || tokenApiModel.RefreshToken == null) { return(BadRequest("Invalid client request")); } string accessToken = tokenApiModel.AccessToken; string refreshToken = tokenApiModel.RefreshToken; var principal = _tokenService.GetPrincipalFromExpiredToken(accessToken); var username = principal.Identity.Name; var user = _appDbContext.Logins.SingleOrDefault(u => u.FirstName == 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; _appDbContext.SaveChanges(); return(new ObjectResult(new { accessToken = newAccessToken, refreshToken = newRefreshToken })); }