NKS
NKS

Reputation: 191

How to limit client IP of a Django app? (Through django and/or PaaS)

I am making a Django app and I wish to enhance the security as well as limit users by making sure only clients only from one IP (say a shared VPN) can access it. I plan to host the app on a PaaS like Digital Ocean App Platform or Heroku.

How can I limit the client IP through:

  1. Django, to prevent other users from accessing the app, and
  2. The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont)

Upvotes: 0

Views: 98

Answers (2)

Ahtisham
Ahtisham

Reputation: 10126

Django, to prevent other users from accessing the app

There is a library know as django-iprestrict specially created for it you can use it.

The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont)

If you have remote access to the server and you are using apache then you can enable apache authenticate that will allow access only to those who have the password. You can set it up by following the digital ocean docs here

Upvotes: 0

user20223018
user20223018

Reputation: 833

I'm not sure about option 2, but for option 1 the best way would be to add middleware which will deny access if the IP is not recognized. Something like this should work:

class IPFilterMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.allowed_ips = settings.ALLOWED_IP_ADDRESSES

    def __call__(self, request):
        # Get the client's IP address from the request, this might not always be correct I believe, needs some testing
        client_ip = request.META.get('REMOTE_ADDR')

        if client_ip in self.allowed_ips:
            return self.get_response(request)
        else:
            return HttpResponseForbidden("Access Denied")

Then the last step would be to add the middleware in the settings.py

Upvotes: 0

Related Questions