From 4445e154a157f24e8cebc520d53dde540227a0d5 Mon Sep 17 00:00:00 2001 From: comalot Date: Mon, 1 Jun 2026 13:19:43 +0800 Subject: [PATCH] fix(frontend): prevent credential loss on page switch and harden auth header Read API key via getStoredApiKey() with trim and try/catch for localStorage safety Avoid silently sending 'Bearer admin' when user has configured a real key Return empty header when no key is available instead of leaking default token Improves reliability of custom endpoint requests after navigation/refresh --- frontend/src/lib/auth.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/frontend/src/lib/auth.ts b/frontend/src/lib/auth.ts index 4c807eab..e5de0dec 100644 --- a/frontend/src/lib/auth.ts +++ b/frontend/src/lib/auth.ts @@ -1,4 +1,20 @@ -export function getAuthHeader() { - const key = localStorage.getItem('qwen2api_key') || 'admin'; - return { Authorization: `Bearer ${key}` }; +/** + * 读取当前会话凭证。 + * - 优先使用 localStorage 中用户显式保存的 key + * - 仅在没有任何配置时回退到 "admin",避免页面切换/刷新后静默丢失凭证 + */ +export function getStoredApiKey(): string { + try { + const stored = localStorage.getItem('qwen2api_key') + if (stored && stored.trim()) return stored.trim() + } catch { + // localStorage 不可用时继续走默认值 + } + return 'admin' +} + +export function getAuthHeader(): Record { + const key = getStoredApiKey() + if (!key) return {} + return { Authorization: `Bearer ${key}` } }