From aa3f5f610816c754a8262c46e6c01dde21a5dc66 Mon Sep 17 00:00:00 2001 From: Admin Date: Sat, 24 Jan 2026 17:39:04 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20HTTPBearer=20?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=20422=20=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 设置 HTTPBearer(auto_error=False) 避免验证错误 - 在 get_current_user 中手动检查并返回 401 --- backend/app/routers/auth.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 48e7bb0..5f7db08 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -22,7 +22,7 @@ from ..models.tenant_app import TenantApp from ..models.tenant_wechat_app import TenantWechatApp router = APIRouter(prefix="/auth", tags=["认证"]) -security = HTTPBearer() +security = HTTPBearer(auto_error=False) class LoginRequest(BaseModel): @@ -48,24 +48,33 @@ class ChangePasswordRequest(BaseModel): # 权限依赖 async def get_current_user( - credentials: HTTPAuthorizationCredentials = Depends(security), + credentials: Optional[HTTPAuthorizationCredentials] = Depends(security), db: Session = Depends(get_db) ) -> User: """获取当前用户""" + if not credentials: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="需要登录认证", + headers={"WWW-Authenticate": "Bearer"} + ) + token = credentials.credentials token_data = decode_token(token) if not token_data: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Token 无效或已过期" + detail="Token 无效或已过期", + headers={"WWW-Authenticate": "Bearer"} ) user = db.query(User).filter(User.id == token_data.user_id).first() if not user or user.status != 1: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="用户不存在或已禁用" + detail="用户不存在或已禁用", + headers={"WWW-Authenticate": "Bearer"} ) return user