fix(auth): migrate tokens from localStorage to httpOnly cookies + CSRF hardening

Backend:
- Auth controller sets httpOnly secure cookies (access_token, refresh_token, goodgo_authenticated) on login/register/refresh
- JWT strategy reads token from cookie first, falls back to Authorization header
- Added POST /auth/logout to clear auth cookies
- Added POST /auth/exchange-token for OAuth callback token-to-cookie exchange
- Refresh endpoint reads refresh_token from cookie (body fallback for backwards compat)
- CSRF middleware excludes auth endpoints (login, register, refresh, exchange-token, logout)

Frontend:
- Removed all localStorage token storage (goodgo_tokens key)
- Removed authGet/authPost/authPatch helpers from api-client (tokens sent via cookies)
- All API calls use credentials:'include' for cookie-based auth
- Updated auth-store: no more token state, uses isAuthenticated flag from cookie
- Updated admin-api, listings-api to remove explicit token parameters
- Updated all pages (admin dashboard, users, KYC, moderation, listings) to remove token passing
- OAuth callbacks use exchange-token endpoint to convert URL tokens to cookies
- Auth provider simplified (no client-side cookie management needed)

Security improvements:
- JWT no longer accessible via JavaScript (XSS-safe)
- Refresh token scoped to /auth path only
- Server-side goodgo_authenticated cookie with SameSite=Lax
- Access token cookie with SameSite=Strict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 06:25:11 +07:00
parent 9583d1cb66
commit 6389dcf78e
19 changed files with 151 additions and 191 deletions

View File

@@ -1,41 +1,22 @@
import { create } from 'zustand';
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { authApi, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { ApiError } from './api-client';
export type { TokenPair };
const TOKEN_KEY = 'goodgo_tokens';
function persistTokens(tokens: TokenPair | null) {
if (typeof window === 'undefined') return;
if (tokens) {
localStorage.setItem(TOKEN_KEY, JSON.stringify(tokens));
} else {
localStorage.removeItem(TOKEN_KEY);
}
}
function loadTokens(): TokenPair | null {
if (typeof window === 'undefined') return null;
const raw = localStorage.getItem(TOKEN_KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
function hasAuthCookie(): boolean {
if (typeof document === 'undefined') return false;
return document.cookie.includes('goodgo_authenticated=1');
}
interface AuthState {
tokens: TokenPair | null;
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (data: LoginPayload) => Promise<void>;
register: (data: RegisterPayload) => Promise<void>;
handleOAuthCallback: (tokens: TokenPair) => Promise<void>;
logout: () => void;
handleOAuthCallback: (accessToken: string, refreshToken: string, expiresIn?: number) => Promise<void>;
logout: () => Promise<void>;
refreshToken: () => Promise<boolean>;
fetchProfile: () => Promise<void>;
initialize: () => Promise<void>;
@@ -43,17 +24,16 @@ interface AuthState {
}
export const useAuthStore = create<AuthState>((set, get) => ({
tokens: null,
user: null,
isAuthenticated: false,
isLoading: false,
error: null,
login: async (data) => {
set({ isLoading: true, error: null });
try {
const tokens = await authApi.login(data);
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.login(data);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng nhập thất bại';
@@ -65,9 +45,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
register: async (data) => {
set({ isLoading: true, error: null });
try {
const tokens = await authApi.register(data);
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.register(data);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng ký thất bại';
@@ -76,11 +55,11 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
handleOAuthCallback: async (tokens) => {
handleOAuthCallback: async (accessToken, refreshToken, expiresIn) => {
set({ isLoading: true, error: null });
try {
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.exchangeToken(accessToken, refreshToken, expiresIn);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng nhập OAuth thất bại';
@@ -89,39 +68,39 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
logout: () => {
persistTokens(null);
set({ tokens: null, user: null, error: null });
logout: async () => {
try {
await authApi.logout();
} catch {
// Clear state even if API call fails
}
set({ user: null, isAuthenticated: false, error: null });
},
refreshToken: async () => {
const { tokens } = get();
if (!tokens?.refreshToken) return false;
try {
const newTokens = await authApi.refresh(tokens.refreshToken);
persistTokens(newTokens);
set({ tokens: newTokens });
await authApi.refresh();
set({ isAuthenticated: true });
return true;
} catch {
get().logout();
set({ user: null, isAuthenticated: false });
return false;
}
},
fetchProfile: async () => {
const { tokens } = get();
if (!tokens?.accessToken) return;
try {
const user = await authApi.getProfile(tokens.accessToken);
set({ user });
const user = await authApi.getProfile();
set({ user, isAuthenticated: true });
} catch (e) {
if (e instanceof ApiError && e.status === 401) {
const refreshed = await get().refreshToken();
if (refreshed) {
const newTokens = get().tokens;
if (newTokens) {
const user = await authApi.getProfile(newTokens.accessToken);
set({ user });
try {
const user = await authApi.getProfile();
set({ user, isAuthenticated: true });
} catch {
set({ user: null, isAuthenticated: false });
}
}
}
@@ -129,9 +108,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
},
initialize: async () => {
const tokens = loadTokens();
if (!tokens) return;
set({ tokens });
if (!hasAuthCookie()) return;
set({ isAuthenticated: true });
await get().fetchProfile();
},