django 有没有办法限制基于IP的应用程序?

ih99xse1  于 2023-04-22  发布在  Go
关注(0)|答案(4)|浏览(121)

我希望能够只允许某些应用程序从公司办公室使用,该办公室具有静态IP。是否有django软件包可以用于此操作?如果有,您知道它是否可以用作额外的安全措施?某些应用程序和这些应用程序中的数据我不希望办公室以外的任何人访问。我已经有相当好的应用程序安全性,但作为一个额外的安全措施,这是一个好的选择?谢谢

p1iqtdky

p1iqtdky1#

只需将这个中间件类包含在settings.py文件中的'MIDDLEWARE_CLASSES'变量下。
还包括变量BLOCKED_IPS = ('123.123.123.123',)变量,其中的值是您希望从站点阻止的IP地址的元组。

"""
   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
bmp9r5qi

bmp9r5qi2#

看起来这就是我要找的...django-iprestrict.readthedocs.io/en/latest/configuration.html该软件包将允许或拒绝默认设置IP白名单或黑名单每个应用程序-

px9o7tmv

px9o7tmv3#

这部分是基于Ramesh K的回答,并在Django 2.2.19中进行了更改。在我使用的服务器上:负载平衡器将接收到的IP地址放入“X-Real-IP”报头(并且还将“X-Forwarded-For”报头作为逗号分隔的IP地址列表传递)。

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)
8aqjt8rx

8aqjt8rx4#

有一个我一直在关注的库,Django IP Restrict,我建议你给予一下,并告诉我们你的经验。

相关问题