feat(auth): 实现 Refresh Token 机制
- 新增 Access Token + Refresh Token 双令牌认证 - 支持 Token 自动刷新和轮转 - 添加登出和撤销所有会话接口 - 前端实现无感刷新和主动刷新定时器
This commit is contained in:
@@ -35,6 +35,22 @@ export function setAuthToken(token: string): void {
|
||||
localStorage.setItem('auth_token', token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store refresh token in localStorage
|
||||
*/
|
||||
export function setRefreshToken(token: string): void {
|
||||
localStorage.setItem('refresh_token', token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store token expiration timestamp in localStorage
|
||||
* Converts expires_in (seconds) to absolute timestamp (milliseconds)
|
||||
*/
|
||||
export function setTokenExpiresAt(expiresIn: number): void {
|
||||
const expiresAt = Date.now() + expiresIn * 1000
|
||||
localStorage.setItem('token_expires_at', String(expiresAt))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication token from localStorage
|
||||
*/
|
||||
@@ -42,12 +58,29 @@ export function getAuthToken(): string | null {
|
||||
return localStorage.getItem('auth_token')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get refresh token from localStorage
|
||||
*/
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem('refresh_token')
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token expiration timestamp from localStorage
|
||||
*/
|
||||
export function getTokenExpiresAt(): number | null {
|
||||
const value = localStorage.getItem('token_expires_at')
|
||||
return value ? parseInt(value, 10) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear authentication token from localStorage
|
||||
*/
|
||||
export function clearAuthToken(): void {
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +94,12 @@ export async function login(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
// Only store token if 2FA is not required
|
||||
if (!isTotp2FARequired(data)) {
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
}
|
||||
|
||||
@@ -77,6 +116,12 @@ export async function login2FA(request: TotpLogin2FARequest): Promise<AuthRespon
|
||||
|
||||
// Store token and user data
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
|
||||
return data
|
||||
@@ -92,6 +137,12 @@ export async function register(userData: RegisterRequest): Promise<AuthResponse>
|
||||
|
||||
// Store token and user data
|
||||
setAuthToken(data.access_token)
|
||||
if (data.refresh_token) {
|
||||
setRefreshToken(data.refresh_token)
|
||||
}
|
||||
if (data.expires_in) {
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
}
|
||||
localStorage.setItem('auth_user', JSON.stringify(data.user))
|
||||
|
||||
return data
|
||||
@@ -108,11 +159,62 @@ export async function getCurrentUser() {
|
||||
/**
|
||||
* User logout
|
||||
* Clears authentication token and user data from localStorage
|
||||
* Optionally revokes the refresh token on the server
|
||||
*/
|
||||
export function logout(): void {
|
||||
export async function logout(): Promise<void> {
|
||||
const refreshToken = getRefreshToken()
|
||||
|
||||
// Try to revoke the refresh token on the server
|
||||
if (refreshToken) {
|
||||
try {
|
||||
await apiClient.post('/auth/logout', { refresh_token: refreshToken })
|
||||
} catch {
|
||||
// Ignore errors - we still want to clear local state
|
||||
}
|
||||
}
|
||||
|
||||
clearAuthToken()
|
||||
// Optionally redirect to login page
|
||||
// window.location.href = '/login';
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh token response
|
||||
*/
|
||||
export interface RefreshTokenResponse {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
token_type: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the access token using the refresh token
|
||||
* @returns New token pair
|
||||
*/
|
||||
export async function refreshToken(): Promise<RefreshTokenResponse> {
|
||||
const currentRefreshToken = getRefreshToken()
|
||||
if (!currentRefreshToken) {
|
||||
throw new Error('No refresh token available')
|
||||
}
|
||||
|
||||
const { data } = await apiClient.post<RefreshTokenResponse>('/auth/refresh', {
|
||||
refresh_token: currentRefreshToken
|
||||
})
|
||||
|
||||
// Update tokens in localStorage
|
||||
setAuthToken(data.access_token)
|
||||
setRefreshToken(data.refresh_token)
|
||||
setTokenExpiresAt(data.expires_in)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke all sessions for the current user
|
||||
* @returns Response with message
|
||||
*/
|
||||
export async function revokeAllSessions(): Promise<{ message: string }> {
|
||||
const { data } = await apiClient.post<{ message: string }>('/auth/revoke-all-sessions')
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -242,14 +344,20 @@ export const authAPI = {
|
||||
logout,
|
||||
isAuthenticated,
|
||||
setAuthToken,
|
||||
setRefreshToken,
|
||||
setTokenExpiresAt,
|
||||
getAuthToken,
|
||||
getRefreshToken,
|
||||
getTokenExpiresAt,
|
||||
clearAuthToken,
|
||||
getPublicSettings,
|
||||
sendVerifyCode,
|
||||
validatePromoCode,
|
||||
validateInvitationCode,
|
||||
forgotPassword,
|
||||
resetPassword
|
||||
resetPassword,
|
||||
refreshToken,
|
||||
revokeAllSessions
|
||||
}
|
||||
|
||||
export default authAPI
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Axios HTTP Client Configuration
|
||||
* Base client with interceptors for authentication and error handling
|
||||
* Base client with interceptors for authentication, token refresh, and error handling
|
||||
*/
|
||||
|
||||
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios'
|
||||
import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
|
||||
import type { ApiResponse } from '@/types'
|
||||
import { getLocale } from '@/i18n'
|
||||
|
||||
@@ -19,6 +19,28 @@ export const apiClient: AxiosInstance = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
// ==================== Token Refresh State ====================
|
||||
|
||||
// Track if a token refresh is in progress to prevent multiple simultaneous refresh requests
|
||||
let isRefreshing = false
|
||||
// Queue of requests waiting for token refresh
|
||||
let refreshSubscribers: Array<(token: string) => void> = []
|
||||
|
||||
/**
|
||||
* Subscribe to token refresh completion
|
||||
*/
|
||||
function subscribeTokenRefresh(callback: (token: string) => void): void {
|
||||
refreshSubscribers.push(callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all subscribers that token has been refreshed
|
||||
*/
|
||||
function onTokenRefreshed(token: string): void {
|
||||
refreshSubscribers.forEach((callback) => callback(token))
|
||||
refreshSubscribers = []
|
||||
}
|
||||
|
||||
// ==================== Request Interceptor ====================
|
||||
|
||||
// Get user's timezone
|
||||
@@ -61,7 +83,7 @@ apiClient.interceptors.request.use(
|
||||
// ==================== Response Interceptor ====================
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
(response: AxiosResponse) => {
|
||||
// Unwrap standard API response format { code, message, data }
|
||||
const apiResponse = response.data as ApiResponse<unknown>
|
||||
if (apiResponse && typeof apiResponse === 'object' && 'code' in apiResponse) {
|
||||
@@ -79,13 +101,15 @@ apiClient.interceptors.response.use(
|
||||
}
|
||||
return response
|
||||
},
|
||||
(error: AxiosError<ApiResponse<unknown>>) => {
|
||||
async (error: AxiosError<ApiResponse<unknown>>) => {
|
||||
// Request cancellation: keep the original axios cancellation error so callers can ignore it.
|
||||
// Otherwise we'd misclassify it as a generic "network error".
|
||||
if (error.code === 'ERR_CANCELED' || axios.isCancel(error)) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean }
|
||||
|
||||
// Handle common errors
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
@@ -120,23 +144,116 @@ apiClient.interceptors.response.use(
|
||||
})
|
||||
}
|
||||
|
||||
// 401: Unauthorized - clear token and redirect to login
|
||||
if (status === 401) {
|
||||
const hasToken = !!localStorage.getItem('auth_token')
|
||||
const url = error.config?.url || ''
|
||||
// 401: Try to refresh the token if we have a refresh token
|
||||
// This handles TOKEN_EXPIRED, INVALID_TOKEN, TOKEN_REVOKED, etc.
|
||||
if (status === 401 && !originalRequest._retry) {
|
||||
const refreshToken = localStorage.getItem('refresh_token')
|
||||
const isAuthEndpoint =
|
||||
url.includes('/auth/login') || url.includes('/auth/register') || url.includes('/auth/refresh')
|
||||
|
||||
// If we have a refresh token and this is not an auth endpoint, try to refresh
|
||||
if (refreshToken && !isAuthEndpoint) {
|
||||
if (isRefreshing) {
|
||||
// Wait for the ongoing refresh to complete
|
||||
return new Promise((resolve, reject) => {
|
||||
subscribeTokenRefresh((newToken: string) => {
|
||||
if (newToken) {
|
||||
// Mark as retried to prevent infinite loop if retry also returns 401
|
||||
originalRequest._retry = true
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
}
|
||||
resolve(apiClient(originalRequest))
|
||||
} else {
|
||||
// Refresh failed, reject with original error
|
||||
reject({
|
||||
status,
|
||||
code: apiData.code,
|
||||
message: apiData.message || apiData.detail || error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
originalRequest._retry = true
|
||||
isRefreshing = true
|
||||
|
||||
try {
|
||||
// Call refresh endpoint directly to avoid circular dependency
|
||||
const refreshResponse = await axios.post(
|
||||
`${API_BASE_URL}/auth/refresh`,
|
||||
{ refresh_token: refreshToken },
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
|
||||
const refreshData = refreshResponse.data as ApiResponse<{
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
}>
|
||||
|
||||
if (refreshData.code === 0 && refreshData.data) {
|
||||
const { access_token, refresh_token: newRefreshToken, expires_in } = refreshData.data
|
||||
|
||||
// Update tokens in localStorage (convert expires_in to timestamp)
|
||||
localStorage.setItem('auth_token', access_token)
|
||||
localStorage.setItem('refresh_token', newRefreshToken)
|
||||
localStorage.setItem('token_expires_at', String(Date.now() + expires_in * 1000))
|
||||
|
||||
// Notify subscribers with new token
|
||||
onTokenRefreshed(access_token)
|
||||
|
||||
// Retry the original request with new token
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${access_token}`
|
||||
}
|
||||
|
||||
isRefreshing = false
|
||||
return apiClient(originalRequest)
|
||||
}
|
||||
|
||||
// Refresh response was not successful, fall through to clear auth
|
||||
throw new Error('Token refresh failed')
|
||||
} catch (refreshError) {
|
||||
// Refresh failed - notify subscribers with empty token
|
||||
onTokenRefreshed('')
|
||||
isRefreshing = false
|
||||
|
||||
// Clear tokens and redirect to login
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
sessionStorage.setItem('auth_expired', '1')
|
||||
|
||||
if (!window.location.pathname.includes('/login')) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return Promise.reject({
|
||||
status: 401,
|
||||
code: 'TOKEN_REFRESH_FAILED',
|
||||
message: 'Session expired. Please log in again.'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No refresh token or is auth endpoint - clear auth and redirect
|
||||
const hasToken = !!localStorage.getItem('auth_token')
|
||||
const headers = error.config?.headers as Record<string, unknown> | undefined
|
||||
const authHeader = headers?.Authorization ?? headers?.authorization
|
||||
const sentAuth =
|
||||
typeof authHeader === 'string'
|
||||
? authHeader.trim() !== ''
|
||||
: Array.isArray(authHeader)
|
||||
? authHeader.length > 0
|
||||
: !!authHeader
|
||||
? authHeader.length > 0
|
||||
: !!authHeader
|
||||
|
||||
localStorage.removeItem('auth_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
localStorage.removeItem('auth_user')
|
||||
localStorage.removeItem('token_expires_at')
|
||||
if ((hasToken || sentAuth) && !isAuthEndpoint) {
|
||||
sessionStorage.setItem('auth_expired', '1')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user