XForwardedMiddleware¶
- class safir.middleware.x_forwarded.XForwardedMiddleware(app: fastapi.applications.FastAPI, *, proxies: Optional[List[ipaddress._BaseNetwork]] = None)¶
Bases:
starlette.middleware.base.BaseHTTPMiddleware
Middleware 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-For
that is not contained within one of the trusted proxy networks.If
X-Forwarded-For
is found andX-Forwarded-Proto
is also present, the corresponding entry ofX-Forwarded-Proto
is used to replace the scheme in the request scope. IfX-Forwarded-Proto
only 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-Host
will be stored asforwarded_host
in the request state if it andX-Forwarded-For
are present. Normally this is not needed since NGINX will pass the originalHost
header 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
dispatch
(request, call_next)Middleware to update the request based on
X-Forwarded-For
.Methods Documentation
- async dispatch(request: starlette.requests.Request, call_next: Callable[[starlette.requests.Request], Awaitable[starlette.responses.Response]]) starlette.responses.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