From 1fdcb9c8b70452afb49c64a260d59ef2633dba63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=87=E8=96=87=E5=AE=89?= Date: Tue, 20 Jan 2026 22:17:09 +0800 Subject: [PATCH] a --- backend/api/auth_deps.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/backend/api/auth_deps.py b/backend/api/auth_deps.py index 75e96fc..aa85c94 100644 --- a/backend/api/auth_deps.py +++ b/backend/api/auth_deps.py @@ -4,7 +4,8 @@ FastAPI 依赖:解析 JWT、获取当前用户、校验 admin、校验 account from __future__ import annotations -from fastapi import Header, HTTPException, Depends +from fastapi import Header, HTTPException, Depends, Security +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from typing import Optional, Dict, Any import os @@ -17,14 +18,21 @@ def _auth_enabled() -> bool: return v not in {"0", "false", "no"} -def get_current_user(authorization: Optional[str] = Header(None, alias="Authorization")) -> Dict[str, Any]: +_bearer_scheme = HTTPBearer(auto_error=False) + + +def get_current_user(credentials: Optional[HTTPAuthorizationCredentials] = Security(_bearer_scheme)) -> Dict[str, Any]: if not _auth_enabled(): # 未启用登录:视为超级管理员(兼容开发/灰度) return {"id": 0, "username": "dev", "role": "admin", "status": "active"} - if not authorization or not authorization.lower().startswith("bearer "): + if not credentials: + raise HTTPException(status_code=401, detail="未登录") + if (credentials.scheme or "").lower() != "bearer": + raise HTTPException(status_code=401, detail="未登录") + token = (credentials.credentials or "").strip() + if not token: raise HTTPException(status_code=401, detail="未登录") - token = authorization.split(" ", 1)[1].strip() try: payload = jwt_decode(token) except Exception: