feat: 登录改用 JWT(access token + refresh token),不再用 cookie
Deploy / deploy (build, debian, 22) (push) Canceled after 0s
Deploy / deploy (build, debian, 22) (push) Canceled after 0s
- 登录返回 15 分钟的 access token(HS256,密钥 JWT_SECRET,未配置则每次启动随机) 和 14 天的 refresh token;请求带 Authorization: Bearer,WebSocket 用 ?token= - refresh token 只存 sha256,放在新表 auth_refresh_token(删除旧的 auth_session); POST /account/refresh 换新的 access token,退出、改密码、封号时作废 - 带了无效或过期的 token 一律 401,前端据此刷新:快过期时提前刷新、并发请求只刷新一次, 401 时刷新后重试一次,refresh token 也失效才退出登录 - 不再用 cookie,去掉 CORS credentials 和写请求的 Origin 校验 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dde976cacb
commit
26827e31d5
21 files changed
+281
-141
No files matched your search
+44
-10
@@ -17,23 +17,57 @@ describe("权限", () => {
|
||||
expect((await adm("GET", "/api/submission/gradebook/?classname=a")).status).toBe(403)
|
||||
})
|
||||
|
||||
test("封号后会话失效", async () => {
|
||||
test("封号后 access token 和 refresh token 都失效", async () => {
|
||||
const id = makeUser("stu")
|
||||
makeUser("boss", "super")
|
||||
const stu = await client("stu")
|
||||
expect((await stu("GET", "/api/account/profile")).json.username).toBe("stu")
|
||||
await (await client("boss"))("PUT", `/api/account/active/${id}`)
|
||||
expect((await stu("GET", "/api/account/profile")).json.username).toBe("")
|
||||
expect((await stu("GET", "/api/account/profile")).status).toBe(401)
|
||||
const anon = await client()
|
||||
const res = await anon("POST", "/api/account/refresh", { refresh_token: stu.tokens.refresh_token })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
describe("JWT 登录", () => {
|
||||
test("登录返回两个 token,refresh token 能换新的 access token", async () => {
|
||||
makeUser("stu")
|
||||
const stu = await client("stu")
|
||||
expect(stu.tokens.access_token.split(".")).toHaveLength(3)
|
||||
expect(get(`SELECT token_hash FROM auth_refresh_token`).token_hash).not.toBe(stu.tokens.refresh_token)
|
||||
|
||||
const anon = await client()
|
||||
const res = await anon("POST", "/api/account/refresh", { refresh_token: stu.tokens.refresh_token })
|
||||
expect(res.status).toBe(200)
|
||||
stu.tokens.access_token = res.json.access_token
|
||||
expect((await stu("GET", "/api/account/profile")).json.username).toBe("stu")
|
||||
})
|
||||
|
||||
test("跨站写请求被拒绝", async () => {
|
||||
const { app } = await import("../src/app")
|
||||
const res = await app.request("/api/account/login", {
|
||||
method: "POST",
|
||||
headers: { origin: "https://evil.example", "content-type": "application/json" },
|
||||
body: "{}",
|
||||
})
|
||||
expect(res.status).toBe(403)
|
||||
test("无效或过期的 access token 返回 401,不带 token 当作未登录", async () => {
|
||||
makeUser("stu")
|
||||
const stu = await client("stu")
|
||||
const { sign } = await import("hono/jwt")
|
||||
const { config } = await import("../src/config")
|
||||
const userId = get(`SELECT id FROM account_user WHERE username = 'stu'`).id
|
||||
stu.tokens.access_token = await sign({ sub: userId, exp: Math.floor(Date.now() / 1000) - 1 }, config.jwtSecret)
|
||||
expect((await stu("GET", "/api/account/profile")).status).toBe(401)
|
||||
stu.tokens.access_token = "garbage"
|
||||
expect((await stu("GET", "/api/account/profile")).status).toBe(401)
|
||||
expect((await (await client())("GET", "/api/account/profile")).json.username).toBe("")
|
||||
})
|
||||
|
||||
test("退出和改密码都会作废 refresh token", async () => {
|
||||
const id = makeUser("stu")
|
||||
makeUser("boss", "super")
|
||||
const anon = await client()
|
||||
const a = await client("stu")
|
||||
expect((await a("POST", "/api/account/logout", { refresh_token: a.tokens.refresh_token })).status).toBe(200)
|
||||
expect((await anon("POST", "/api/account/refresh", { refresh_token: a.tokens.refresh_token })).status).toBe(401)
|
||||
|
||||
const b = await client("stu")
|
||||
await (await client("boss"))("PUT", `/api/account/${id}`, { password: "newpass1" })
|
||||
expect((await anon("POST", "/api/account/refresh", { refresh_token: b.tokens.refresh_token })).status).toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -48,9 +48,9 @@ export function makeSubmission(userId: number, taskId: number, score = 0, create
|
||||
|
||||
export const uuid = (hex: string) => uuidOut(hex)
|
||||
|
||||
/** 登录后返回一个带 cookie 的请求函数 */
|
||||
/** 登录后返回一个带 access token 的请求函数,tokens 是登录拿到的 token */
|
||||
export async function client(username?: string) {
|
||||
let cookie = ""
|
||||
const tokens = { access_token: "", refresh_token: "" }
|
||||
if (username) {
|
||||
const res = await app.request("/api/account/login", {
|
||||
method: "POST",
|
||||
@@ -58,10 +58,11 @@ export async function client(username?: string) {
|
||||
body: JSON.stringify({ username, password: PASSWORD }),
|
||||
})
|
||||
if (res.status !== 200) throw new Error(`login failed: ${res.status}`)
|
||||
cookie = res.headers.get("set-cookie")!.split(";")[0]!
|
||||
Object.assign(tokens, await res.json())
|
||||
}
|
||||
return async (method: string, path: string, body?: unknown) => {
|
||||
const headers: Record<string, string> = { cookie }
|
||||
const request = async (method: string, path: string, body?: unknown) => {
|
||||
const headers: Record<string, string> = {}
|
||||
if (tokens.access_token) headers.authorization = `Bearer ${tokens.access_token}`
|
||||
if (body !== undefined) headers["content-type"] = "application/json"
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
@@ -75,4 +76,5 @@ export async function client(username?: string) {
|
||||
} catch {}
|
||||
return { status: res.status, json, text, headers: res.headers }
|
||||
}
|
||||
return Object.assign(request, { tokens })
|
||||
}
|
||||
Reference in new issue
Block a user