I'm new with FastAPI and Starlette, and I'm struggling to make a middleware that tampers the incoming request. I'm trying to parse the X-Forwarded-Uri and the X-Forwarded-Host headers and modify the incoming request so that those are taken into account instead of the actual request.
My attempt is the following piece of code:
class XForwardedMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
for header, value in request.scope["headers"]:
if header == b"x-forwarded-uri":
uri = URL(value.decode("utf-8"))
request.scope["path"] = uri.path
request.scope["query_string"] = uri.query.encode("utf-8")
if header == b"x-forwarded-host":
request.scope["headers"].append((b"host", value))
response = await call_next(request)
return response
However, it fails to identify the base_url
of the request and fails when I use request.url_for('/some/route')
as it returns the location of the actual request instead of the 'X-Fowarded' one.