I want to create a localhost-only API in Django and I’m trying to find a way to restrict the access to a view only from the server itself (localhost)? I’ve tried using:
- ‘HTTP_HOST’,
- ‘HTTP_X_FORWARDED_FOR’,
- ‘REMOTE_ADDR’,
- ‘SERVER_ADDR’
but with no luck.
Is there any other way?
The problem is a bit more complex than just checking a variable. To identify the client IP address, you’ll need
and then to compare it with the
request.get_host(). But you might take into account that the server might be started on 0.0.0.0:80, so then you’ll probably need to do:and to compare this with let’s say
But you’ll need to process lots of edge-cases with these headers and values.
A much simpler approach could be to have a reverse proxy in front of your app, that sends let’s say some custom_header like
X_SOURCE=internet. Then you can setup the traffic from internet to goes through the proxy, while the local traffic(in your local network) to go directly to the web server. So then if you want to have access to a specific view only from your local network, just check this header:But again – this is the ‘firewall approach’, and it will require a some more setup, and to be sure that there is no possible access to the app from outside, that doesn’t go through the reverse proxy..