XForwardedMiddleware

class safir.middleware.x_forwarded.XForwardedMiddleware(app: FastAPI, *, proxies: Optional[List[_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 and X-Forwarded-Proto is also present, the corresponding entry of X-Forwarded-Proto is stored as forwarded_proto in the request state. If X-Forwarded-Proto only has one entry (ingress-nginx has this behavior), that one entry will be stored as forwarded_proto.

The contents of X-Forwarded-Host will be stored as forwarded_host in the request state if it and X-Forwarded-For are present.

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.

call_next(request)

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 call_next(request: starlette.requests.Request) starlette.responses.Response
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