XForwardedMiddleware¶
- class safir.middleware.x_forwarded.XForwardedMiddleware(app: FastAPI, *, proxies: Optional[List[_BaseNetwork]] = None)¶
Bases:
starlette.middleware.base.BaseHTTPMiddlewareMiddleware to update the request based on
X-Forwarded-For.The remote IP address will be replaced with the right-most IP address in
X-Forwarded-Forthat is not contained within one of the trusted proxy networks.If
X-Forwarded-Foris found andX-Forwarded-Protois also present, the corresponding entry ofX-Forwarded-Protois used to replace the scheme in the request scope. IfX-Forwarded-Protoonly has one entry (ingress-nginx has this behavior), that one entry will become the new scheme in the request scope.The contents of
X-Forwarded-Hostwill be stored asforwarded_hostin the request state if it andX-Forwarded-Forare present. Normally this is not needed since NGINX will pass the originalHostheader without modification.- Parameters
proxies (List[
ipaddress._BaseNetwork], optional) – The networks of the trusted proxies. If not specified, defaults to the empty list, which means only the immediately upstream proxy will be trusted.
Methods Summary
__call__(scope, receive, send)Call self as a function.
dispatch(request, call_next)Middleware to update the request based on
X-Forwarded-For.Methods Documentation
- async __call__(scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]], send: Callable[[MutableMapping[str, Any]], Awaitable[None]]) None¶
Call self as a function.
- async dispatch(request: Request, call_next: Callable[[Request], Awaitable[Response]]) Response¶
Middleware to update the request based on
X-Forwarded-For.- Parameters
request (
fastapi.Request) – The incoming request.call_next (
typing.Callable) – The next step in the processing stack.
- Returns
response – The response with additional information about proxy headers.
- Return type
fastapi.Response