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,6 +1,6 @@
|
||||
import { NavLink, Outlet, useNavigate } from 'react-router-dom'
|
||||
import { LayoutDashboard, Users, PawPrint, MessageSquare, MessagesSquare, FileText, ClipboardList, Sparkles, MessageCircle, Crown, LogOut } from 'lucide-react'
|
||||
import { clearToken } from '@/lib/api'
|
||||
import { api, clearToken } from '@/lib/api'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
@@ -20,6 +20,8 @@ const nav = [
|
||||
export default function Layout() {
|
||||
const navigate = useNavigate()
|
||||
function logout() {
|
||||
// 服务端作废刷新令牌,成不成都要本地清掉
|
||||
api.logout().catch(() => {})
|
||||
clearToken()
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
@@ -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'),
|
||||
|
||||
|
||||
@@ -7,19 +7,24 @@ import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
|
||||
export default function Login() {
|
||||
const [username, setUsername] = useState('sundynix')
|
||||
const [password, setPassword] = useState('sundynix')
|
||||
// 不预填账号密码:预填等于把后台凭证写在页面上
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!username.trim() || !password) {
|
||||
setError('请输入账号和密码')
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await api.login(username, password)
|
||||
setToken(res.token)
|
||||
const res = await api.login(username.trim(), password)
|
||||
setToken(res.token, res.refresh_token)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.message || '登录失败')
|
||||
@@ -39,11 +44,22 @@ export default function Login() {
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label>账号</Label>
|
||||
<Input value={username} onChange={(e) => setUsername(e.target.value)} />
|
||||
<Input
|
||||
value={username}
|
||||
autoComplete="username"
|
||||
placeholder="请输入账号"
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>密码</Label>
|
||||
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
|
||||
<Input
|
||||
type="password"
|
||||
value={password}
|
||||
autoComplete="current-password"
|
||||
placeholder="请输入密码"
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
|
||||
@@ -19,7 +19,7 @@ export default defineConfig({
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
'/api': 'http://localhost:9090',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user