from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import Response # 鉴权中间件 class SecurityMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # 获取请求路径 path = request.url.path # 获取请求头 Token # token = request.headers.get("token") # if not token: # return Response("Token is required", status_code=401) # 获取请求参数 query_params = request.query_params # 获取请求体 body = await request.body() # 获取请求方法 method = request.method # 获取请求IP ip = request.client.host return await call_next(request) def add_security_middleware(app): app.add_middleware(SecurityMiddleware)