支持 标准Bearer格式和直接token格式(
This commit is contained in:
@@ -38,6 +38,8 @@ from fastapi import Request, Response as FastAPIResponse, HTTPException, status
|
||||
from fastapi.responses import JSONResponse, FileResponse, StreamingResponse
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from fastapi.security.base import SecurityBase
|
||||
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
from peewee import OperationalError
|
||||
from werkzeug.http import HTTP_STATUS_CODES
|
||||
@@ -51,8 +53,35 @@ from api.db.services.llm_service import LLMService
|
||||
from api.db.services.tenant_llm_service import TenantLLMService
|
||||
from api.utils.json import CustomJSONEncoder, json_dumps
|
||||
|
||||
# 自定义认证方案,支持不传Bearer格式
|
||||
class CustomHTTPBearer(SecurityBase):
|
||||
def __init__(self, *, scheme_name: str = None, auto_error: bool = True):
|
||||
self.scheme_name = scheme_name or self.__class__.__name__
|
||||
self.auto_error = auto_error
|
||||
# 添加 model 属性用于 OpenAPI 文档生成
|
||||
self.model = HTTPBearer()
|
||||
|
||||
async def __call__(self, request: Request) -> HTTPAuthorizationCredentials:
|
||||
authorization: str = request.headers.get("Authorization")
|
||||
if not authorization:
|
||||
if self.auto_error:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not authenticated"
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
# 支持Bearer格式和直接token格式
|
||||
if authorization.startswith("Bearer "):
|
||||
token = authorization[7:] # 移除"Bearer "前缀
|
||||
else:
|
||||
token = authorization # 直接使用token
|
||||
|
||||
return HTTPAuthorizationCredentials(scheme="Bearer", credentials=token)
|
||||
|
||||
# FastAPI 安全方案
|
||||
security = HTTPBearer()
|
||||
security = CustomHTTPBearer()
|
||||
from api.utils import get_uuid
|
||||
from rag.utils.mcp_tool_call_conn import MCPToolCallSession, close_multiple_mcp_toolcall_sessions
|
||||
|
||||
|
||||
Reference in New Issue
Block a user