我正在制作一个 Django 应用程序,我希望通过确保只有来自一个 IP(例如共享 VPN)的客户端才能访问它来增强安全性并限制用户。我计划将应用程序托管在 PaaS 上,例如 Digital Ocean App Platform 或 Heroku。
如何限制客户端IP:
我不确定选项 2,但对于选项 1,最好的方法是添加中间件,如果无法识别 IP,该中间件将拒绝访问。像这样的东西应该有效:
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")
那么最后一步就是在
settings.py
中添加中间件