I built a REST API and deployed it to Heroku. Then I published it on RapidAPI marketplace. RapidAPI sends a special header called x-rapidapi-proxy-secret
that I use to make sure requests only come through their platform.
I added middleware to check this header:
api = FastAPI()
proxy_secret = os.environ.get("SECRET_KEY", None)
@api.middleware("http")
async def validate_rapidapi_header(req: Request, next_call):
if proxy_secret:
request_headers = req.headers
print(request_headers)
if (
"X-RapidAPI-Proxy-Secret" not in request_headers
or request_headers["X-RapidAPI-Proxy-Secret"] != proxy_secret
):
return PlainTextResponse(
"API access denied", status_code=403
)
result = await next_call(req)
return result
The problem is that when RapidAPI sends a request to my Heroku app, the first request has the x-rapidapi-proxy-secret
header. But then Heroku does an internal redirect and the second request is missing this header completely.
Here’s what I see in my logs:
2022-05-13T09:49:58.117345+00:00 app[web.1]: Headers({'host': 'myapi.herokuapp.com', 'x-rapidapi-proxy-secret': '**hidden**', 'x-rapidapi-user': 'testuser'})
2022-05-13T09:49:58.117942+00:00 app[web.1]: 176.12.151.31:0 - "GET /data?query=test" 307
2022-05-13T09:49:59.163686+00:00 app[web.1]: Headers({'host': 'myapi.herokuapp.com', 'x-rapidapi-key': '**hidden**'})
2022-05-13T09:49:59.163820+00:00 app[web.1]: 176.12.151.31:0 - "GET /data/?query=test HTTP/1.1" 403
The first request has the proxy secret header but gets a 307 redirect. The second request after redirect is missing the header so my middleware blocks it with 403.
Is there any way to make Heroku keep all headers when it redirects requests? Or should I handle this proxy secret validation differently?