public async Task <IActionResult> LoginUser(UserLoginForm loginForm) { var user = await _userManager.FindByNameAsync(loginForm.UserName); var result = await _signInManager.CheckPasswordSignInAsync(user, loginForm.Password, false); if (result.Succeeded) { var appUser = await _userManager.Users.FirstOrDefaultAsync( u => u.NormalizedUserName == loginForm.UserName.ToUpper()); var roles = await _userManager.GetRolesAsync(appUser); var userProfile = _mapper.Map <UserProfileDto>(appUser); var tokenKey = _securityConfigurations.tokenKey; var issuer = _securityConfigurations.Issuer; var appKey = _securityConfigurations.appKey; var token = TokensGenerator.GenerateJwtToken(appUser, roles, tokenKey, issuer); var refreshToken = TokensGenerator.GenerateRefreshToken(); HttpContext.AddCookies(token, appKey); HttpContext.AddCookies(refreshToken, $"{appKey}Refresh"); var existingToken = await _tokenRepository.FindItemAsync( t => t.UserId == appUser.Id && t.DeviceName == Request.Headers["device-info"].ToString()); if (existingToken != null) { _logger.LogWarning($"User with Id {appUser.Id} has already logged in from this device, old refresh token will be removed."); await _tokenRepository.RemoveItemAsync(existingToken); _logger.LogInformation($"Old refresh token for user with Id {appUser.Id} removed from database."); } await _tokenRepository.AddItemAsync( new RefreshToken { Id = GuidCreator.CreateGuid(), TokenValue = refreshToken, DeviceName = Request.Headers["device-info"], UserId = appUser.Id }); _logger.LogInformation($"User with id {appUser.Id} successfully logged in."); return(Ok(new { user = userProfile, token, refreshToken })); } return(Unauthorized()); }
public async Task <IActionResult> RefreshToken([FromHeader] string RefreshToken) { var refreshToken = await _tokenRepository.FindItemAsync( t => t.TokenValue == RefreshToken); if (refreshToken != null) { await _tokenRepository.RemoveItemAsync(refreshToken); refreshToken.TokenValue = TokensGenerator.GenerateRefreshToken(); await _tokenRepository.AddItemAsync(refreshToken); var user = await _userManager.FindByIdAsync(refreshToken.UserId.ToString()); var roles = await _userManager.GetRolesAsync(user); var userProfile = _mapper.Map <UserProfileDto>(user); var tokenKey = _securityConfigurations.tokenKey; var issuer = _securityConfigurations.Issuer; var appKey = _securityConfigurations.appKey; var token = TokensGenerator.GenerateJwtToken(user, roles, tokenKey, issuer); HttpContext.AddCookies(token, appKey); HttpContext.AddCookies(refreshToken.TokenValue, $"{appKey}Refresh"); _logger.LogInformation($"Token for user {refreshToken.UserId} successfully refreshed."); return(Ok(new { user = userProfile, token, refreshToken.TokenValue })); } _logger.LogError($"Token {RefreshToken} doesn't exist in database.!"); return(StatusCode(401)); }