feat(auth): access token 缩到 2 小时 + refresh token 机制
后台登录框原来预填了 sundynix/sundynix,等于把凭证写在页面上,去掉。 令牌改为 access(2h) + refresh 两段式: - 新表 sundynix_refresh_tokens,只存 sha256,明文只在签发时返回一次 - 有效期:小程序 30 天、后台 7 天 - 新接口 /api/auth/refresh|logout、/api/admin/refresh|logout 安全约定: - 每次续期都轮换刷新令牌,旧的立即作废 - 作废后 60 秒内再到达算并发重试放行,超过则判定泄露、吊销该账号全部会话 - 主动退出与被连坐吊销的令牌不吃宽限期,否则「吊销全部」形同虚设 - 禁用用户时一并吊销刷新令牌,最多 2 小时彻底失去访问 两端请求层都做了单飞续期:并发请求同时 401 只发一次 refresh, 否则刷新令牌会被并发轮换掉互相打架。小程序续期失败回退 wx.login, 登录/续期请求标 noAuthRetry,避免登录失败(同样返回 40100)触发自我套娃。 顺带修掉 vite 代理仍指向 8080 的遗留(端口早已改 9090)。 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,15 +1,21 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const TOKEN_KEY = 'pets_admin_token'
|
||||
const REFRESH_KEY = 'pets_admin_refresh'
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
export function setToken(t: string) {
|
||||
export function getRefreshToken() {
|
||||
return localStorage.getItem(REFRESH_KEY) || ''
|
||||
}
|
||||
export function setToken(t: string, refresh?: string) {
|
||||
localStorage.setItem(TOKEN_KEY, t)
|
||||
if (refresh) localStorage.setItem(REFRESH_KEY, refresh)
|
||||
}
|
||||
export function clearToken() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_KEY)
|
||||
}
|
||||
|
||||
const http = axios.create({ baseURL: '/api' })
|
||||
@@ -20,15 +26,57 @@ http.interceptors.request.use((cfg) => {
|
||||
return cfg
|
||||
})
|
||||
|
||||
// access token 只有 2 小时,过期后拿 refresh token 换新的。
|
||||
// 用单飞(single-flight)保证并发请求只触发一次刷新,否则刷新令牌会被并发轮换掉。
|
||||
let refreshing: Promise<string> | null = null
|
||||
|
||||
function refreshAccessToken(): Promise<string> {
|
||||
if (!refreshing) {
|
||||
const rt = getRefreshToken()
|
||||
refreshing = (
|
||||
rt
|
||||
? axios.post('/api/admin/refresh', { refresh_token: rt }).then((r) => {
|
||||
const body = r.data
|
||||
if (!body || body.code !== 0) throw new Error(body?.message || '续期失败')
|
||||
setToken(body.data.token, body.data.refresh_token)
|
||||
return body.data.token as string
|
||||
})
|
||||
: Promise.reject(new Error('没有刷新令牌'))
|
||||
).finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
}
|
||||
return refreshing
|
||||
}
|
||||
|
||||
function logout() {
|
||||
clearToken()
|
||||
if (location.pathname !== '/admin/login') location.href = '/admin/login'
|
||||
}
|
||||
|
||||
// 这几个接口本身就可能返回 40100(密码错、刷新令牌失效),不能再触发刷新,否则会绕圈
|
||||
const NO_REFRESH = ['/admin/login', '/admin/refresh', '/admin/logout']
|
||||
|
||||
// 统一响应 {code,message,data}:成功返回 data,失败抛错
|
||||
http.interceptors.response.use(
|
||||
(resp) => {
|
||||
async (resp) => {
|
||||
const body = resp.data
|
||||
if (body && typeof body === 'object' && 'code' in body) {
|
||||
if (body.code === 0) return body.data
|
||||
if (body.code === 40100) {
|
||||
clearToken()
|
||||
if (location.pathname !== '/admin/login') location.href = '/admin/login'
|
||||
const cfg = resp.config as typeof resp.config & { _retried?: boolean }
|
||||
const skip = NO_REFRESH.some((p) => (cfg.url || '').startsWith(p))
|
||||
if (!skip && !cfg._retried) {
|
||||
cfg._retried = true
|
||||
try {
|
||||
const t = await refreshAccessToken()
|
||||
cfg.headers.Authorization = `Bearer ${t}`
|
||||
return await http.request(cfg)
|
||||
} catch {
|
||||
/* 续期失败,落到下面退出登录 */
|
||||
}
|
||||
}
|
||||
if (!skip) logout()
|
||||
}
|
||||
return Promise.reject(new Error(body.message || '请求失败'))
|
||||
}
|
||||
@@ -46,7 +94,11 @@ export interface Page<T> {
|
||||
|
||||
export const api = {
|
||||
login: (username: string, password: string) =>
|
||||
http.post<any, { token: string; admin: any }>('/admin/login', { username, password }),
|
||||
http.post<any, { token: string; refresh_token: string; expires_in: number; admin: any }>(
|
||||
'/admin/login',
|
||||
{ username, password },
|
||||
),
|
||||
logout: () => http.post('/admin/logout', { refresh_token: getRefreshToken() }),
|
||||
me: () => http.get<any, any>('/admin/me'),
|
||||
stats: () => http.get<any, { users: number; pets: number; posts: number; records: number }>('/admin/stats'),
|
||||
|
||||
|
||||
Reference in New Issue
Block a user