fix(auth): CSRF/鉴权中间件兼容反向代理路径前缀 + 无会话请求豁免
清空浏览器缓存后(尤其 token 换登录)报「CSRF token missing」。根因: 反向代理把请求转发到带前缀的路径(如 /xxx/api/v1/auth/login/token), FastAPI 用 root_path 剥前缀做路由,但 Starlette 中间件跑在路由之前, 看到的仍是带前缀的 path,导致 CSRF 豁免名单与公开路径白名单(精确/前缀 匹配)全部失配。清缓存前靠 localStorage 残留 token 当 Bearer 绕过 CSRF, 清掉后裸奔才暴露。 - 新增 proxy_path.app_relative_path:匹配前按 root_path / X-Forwarded-Prefix 剥掉代理前缀(无前缀时 no-op)。 - csrf_middleware:should_check_csrf / is_auth_endpoint 改用应用相对路径; 补上漏收的 /api/v1/auth/login/token 豁免;新增「无 access_token 会话 cookie 则跳过 CSRF」兜底(无会话请求不存在可被跨站伪造利用的会话)。 - auth_middleware:公开路径判断改用应用相对路径,避免 /xxx/api/public/* 分享页被误判 401。 - langgraph_auth:无 access_token cookie 时跳过 CSRF,与网关链路一致。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
413f92e270
commit
3178b4c45e
4 files changed
+82
-5
No files matched your search
@@ -40,6 +40,13 @@ def _check_csrf(request) -> None:
|
||||
# CSRF protection is for cookie-auth browser flows.
|
||||
return
|
||||
|
||||
# No cookie-based session → nothing for a cross-site forgery to ride, so
|
||||
# CSRF is moot. Enforcing it here would reject a freshly-loaded browser
|
||||
# (just cleared its cookies) before it can authenticate; such a request is
|
||||
# rejected as unauthenticated (401) below anyway.
|
||||
if not request.cookies.get("access_token"):
|
||||
return
|
||||
|
||||
cookie_token = request.cookies.get("csrf_token")
|
||||
header_token = request.headers.get("x-csrf-token")
|
||||
|
||||
|
||||
Reference in new issue
Block a user