Django REST API set allowed hosts for individual endpoints

Viewed 262

I would like to have different values for ALLOWED_HOSTS for different Django REST API endpoints. Is this possible? Here are more details:

I have a setup consisting of a Django REST API backend, a React frontend, a Postgresdb and nginx, each running in a docker container, managed by docker compose. I am exposing Django API endpoints that are accessed by the frontend from the user's browser, so I am adding the domain of the frontend to allowed hosts. However, I have one specific API endpoint that should only accept requests from the frontend docker container but never accept requests from outside. It should only be used for communication between the frontend and the backend container. So in this case i would have to restrict allowed hosts to the ip of the docker container. Both settings are possible and working, but I can only choose one of both in the global Django settings. My question is: Is it possible to set allowed hosts for an individual endpoint/url?

I suppose if there is no clean way of doing it I could run a manual check using HttpRequest.get_host() to verify the request host against the container name?

1 Answers

It's certainly possible.

In a pure Django context, I'd implement this as a Django middleware that intercepts the request, looks at the path and the request host, source IP and does what it needs to.

In a Django REST Framework context, I'd implement this as an additional authentication class, since it will then have access to the Django REST Framework context if required.

Finally, I'd recommend also protecting this "secret" endpoint with additional authentication – the simplest might be an additional secret header (X-Nik-Secret: very? ;-) ) that is known to the frontend container. That check can similarly be implemented in middleware or authentication.

Related