From a08d725104281b8ed698f79dd6e166137fea911b Mon Sep 17 00:00:00 2001 From: canglan Date: Tue, 14 Apr 2026 14:19:19 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E6=BB=9Abug=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .cospec/plan/changes/fix-admin-multi-issues/task.md | 11 +++++++++++ frontend/assets/js/common.js | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/.cospec/plan/changes/fix-admin-multi-issues/task.md b/.cospec/plan/changes/fix-admin-multi-issues/task.md index 58ed56e..4ff78dd 100644 --- a/.cospec/plan/changes/fix-admin-multi-issues/task.md +++ b/.cospec/plan/changes/fix-admin-multi-issues/task.md @@ -191,3 +191,14 @@ - 在 401 处理中添加路径判断:如果当前已在 `/index.php`(登录页),不执行重定向 - 添加重定向频率限制:使用 sessionStorage 记录最近一次 401 重定向时间,如果 5 秒内重复 401,停止重定向并在控制台输出警告 - 清除认证信息后,在跳转前添加延迟或在 URL 中添加标记参数,防止浏览器缓存导致的循环 + +### 阶段 8:修复 302 循环 - 401 时同步清除 PHP Session + +- [x] 8.1 修复 302 循环 - 401 时同步清除 PHP Session + 【目标对象】`frontend/assets/js/common.js` + 【修改目的】修复 PHP Session 与 JWT Token 不同步导致的 302 无限重定向循环。当 JWT Token 无效(如后端重启后 Redis 清空)导致 API 返回 401 时,`clearAuth()` 只清除了 localStorage 中的 JWT Token,但 PHP Session 仍然有效,导致 `index.php` 第 15-23 行检测到有效 Session 后又 302 重定向到 dashboard,形成循环。 + 【修改方式】在 `apiRequest` 函数的 401 处理逻辑中,`clearAuth()` 之后增加对 `/api/clear_session.php` 的 POST 调用,以同步清除 PHP Session + 【修改内容】 + - 在 `clearAuth()` 调用后、路径检查之前,添加 `fetch('/api/clear_session.php', { method: 'POST', headers: { 'Content-Type': 'application/json' } })` 调用 + - 使用 try-catch 包裹,失败时仅输出 console.warn 警告,不阻塞后续重定向逻辑 + - `/api/clear_session.php` 是同源路径(由 Nginx 直接处理,不经过后端 FastAPI),不需要 Authorization header,也不会触发跨域问题 diff --git a/frontend/assets/js/common.js b/frontend/assets/js/common.js index 4e01090..a95ba35 100644 --- a/frontend/assets/js/common.js +++ b/frontend/assets/js/common.js @@ -52,6 +52,16 @@ async function apiRequest(url, options = {}) { if (response.status === 401) { clearAuth(); + // 同步清除 PHP Session,防止 index.php 302 重定向循环 + try { + await fetch('/api/clear_session.php', { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }); + } catch (e) { + console.warn('[Auth] 清除PHP Session失败:', e); + } + // 防循环机制:检查是否已在登录页 if (window.location.pathname === '/index.php' || window.location.pathname === '/') { console.warn('[Auth] 已在登录页收到401,停止重定向');