public async Task <AuthenticationResponse> AuthenticateAsync(AuthenticationRequest request, string ipAddress) { _logger.LogDebug("Authenticating a user"); // get a user if user exist create token for that user var user = _context.Api_Users.SingleOrDefault(a => a.Username == request.Username); if (user == null) { return(null); } if (!CryptoService.VerifyPassword(request.Password, user.PasswordHash, user.Salt)) { return(null); } var jwtToken = CreateJwtToken(user); var refreshToken = CreateRefreshToken(ipAddress); user.Refresh_Tokens.Add(refreshToken); _context.Update(user); await _context.SaveChangesAsync(); var response = new AuthenticationResponse(user, jwtToken, refreshToken.Token); if (_jwtOptions.KeepSecretValues) { return(response.HideKeys()); } return(response); }
public AuthenticationResponse?RefreshToken(string token, string ipAddress) { _logger.LogDebug("Refreshing token"); var user = _context.Api_Users.SingleOrDefault(u => u.Refresh_Tokens.Any(t => t.Token == token)); if (user == null) { return(null); } var refreshToken = user.Refresh_Tokens.Single(x => x.Token == token); // return null if token is no longer active if (!refreshToken.IsActive) { return(null); } // replace old refresh token with a new one and save var newRefreshToken = CreateRefreshToken(ipAddress); refreshToken.Revoked = DateTime.UtcNow; refreshToken.RevokedByIp = ipAddress; refreshToken.ReplacedByToken = newRefreshToken.Token; user.Refresh_Tokens.Add(newRefreshToken); //TODO _context.Update(user); _context.SaveChanges(); // generate new jwt var jwtToken = CreateJwtToken(user); var response = new AuthenticationResponse(user, jwtToken, newRefreshToken.Token); if (_jwtOptions.KeepSecretValues) { return(response.HideKeys()); } return(response); }