[Django]-Is there a way to restrict apps based on IP?

1๐Ÿ‘

โœ…

It looks like this is what Iโ€™m looking forโ€ฆ
django-iprestrict.readthedocs.io/en/latest/configuration.html
That package will let you either allow or deny by default and set IP whitelists or blacklists per app โ€“

๐Ÿ‘คuser3005684

6๐Ÿ‘

Just include this middleware class under the 'MIDDLEWARE_CLASSES' variable in your settings.py file.

Also include the variable BLOCKED_IPS = ('123.123.123.123',) variable, where the value is a tuple of IP addresses you want blocked from your site.

  """
   simple middlware to block IP addresses via settings 
   variable BLOCKED_IPS
  """
  from django.conf import settings
  from django import http

  class BlockedIpMiddleware(object):
      def process_request(self, request):
          if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
             return http.HttpResponseForbidden('<h1>Forbidden</h1>')
          return None
๐Ÿ‘คRamesh K

1๐Ÿ‘

There is a library I have been having my eye on, Django IP Restrict, I suggest you give a try and tell us your experiance too with it.

๐Ÿ‘คJet Ezra

0๐Ÿ‘

This is partly based on answer by Ramesh K, with changes for Django 2.2.19. On the server that I use: the load-balancer puts the IP address received into the "X-Real-IP" header (and also passes the "X-Forwarded-For" header as a comma-separated list of IP addresses). Then the "REMOTE_ADDR" contains load-balancer address, rather than the actual remote address.

from django.conf import settings
from django import http

class BlockedIpMiddleware:
   def __init__(self, get_response):
      # One-time configuration and initialization, when the webserver starts.
      self.get_response = get_response


   def __call__(self, request):
      # Code to be executed for each request before the view (and later
      # middleware) are called.

      # if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
      
      if request.META['HTTP_X_REAL_IP'] in settings.BLOCKED_IPS:
         return http.HttpResponseForbidden('<h1>Forbidden</h1>')

      return self.get_response(request)

Leave a comment