Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict access to a Django view, only from the server itself (localhost)

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?

like image 575
user967722 Avatar asked Dec 15 '22 21:12

user967722


2 Answers

You could configure your webserver (Apache, Nginx etc) to bind only to localhost.

This would work well if you want to restrict access to all views, but if you want to allow access to some views from remote users, then you'd have to configure a second Django project.

like image 124
Alasdair Avatar answered May 12 '23 03:05

Alasdair


The problem is a bit more complex than just checking a variable. To identify the client IP address, you'll need

request.META['REMOTE_ADDR'] -- The IP address of the client.

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:

import socket
socket.gethostbyaddr(request.META['REMOTE_ADDR'])

and to compare this with let's say

socket.gethostbyaddr("127.0.0.1")

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:

if 'X_SOURCE' in request.META:
    # request is coming from internet, and not local network....
else:
    # presumably we have a local request...

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..

like image 35
Tisho Avatar answered May 12 '23 04:05

Tisho