返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Django

Implementing an Admin Backend IP Whitelist with Django Middleware

Preface Django's built-in Admin management backend is very convenient, but there really are quite a few security issues in actual production environments. Regarding admin security protection, I previously researched and implemented adding a login captcha and rate limiting to admin. You can refer to this article: Adding Captcha and Multiple Login Attempt Limits to Django Admin However, it's much better if it's only used internally, so we can implement IP filtering through Django middleware. Therefore this article involves two knowledge points: one is Django middleware, and the other is P

曦远 (DealiAxy)约 9 分钟
目录5 个章节

Preface

Django's built-in Admin management backend is very convenient, but there really are quite a few security issues in actual production environments. Regarding admin security protection, I previously researched and implemented adding a login captcha and rate limiting to admin. You can refer to this article: Adding Captcha and Multiple Login Attempt Limits to Django Admin

However, it's much better if it's only used internally, so we can implement IP filtering through Django middleware. Therefore this article involves two knowledge points: one is Django middleware, and the other is how Python handles IP as a data structure.

Let's get into the main topic~

Django Middleware

The concept and usage of middleware are not the focus of this article; please refer to the official documentation yourself—it's written very clearly and easy to understand.

First, we create a new Python package: middleware, and create a Python file admin_secure.py to write our middleware:

import ipaddress

from django.conf import settings
from django.http.response import HttpResponseForbidden

class AdminSecureMiddleware(object):
    """
    Admin 安全中间件
    用于限制可访问 admin 管理后台的IP段
    """

    admin_url = f'/{settings.URL_PREFIX}admin'

    allow_networks = [
        ipaddress.ip_network('10.53.0.0/20'),
    ]

    allow_addresses = []

    @classmethod
    def get_allow_addresses(cls):
        if len(cls.allow_addresses) > 0:
            return cls.allow_addresses

        for network in cls.allow_networks:
            for ip in network:
                cls.allow_addresses.append(ip)

        return cls.allow_addresses

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        ip_addr = ipaddress.ip_address(request.META.get('REMOTE_ADDR'))

        if request.path.startswith(self.admin_url):
            if ip_addr not in self.get_allow_addresses():
                return HttpResponseForbidden()

        return response

Note the code above: you can add the allowed IP network segments in allow_networks , then enable this middleware in settings.py and you're good to go.

This then brings up the second knowledge point covered in this article, which is Python's ipaddress operations.

ipaddress Module

I suddenly feel like slacking off, hahahahaha~

Because this part is really quite simple. The official documentation is: https://docs.python.org/zh-cn/3/howto/ipaddress.html

You haven't given your college computer networking knowledge back to the teacher yet, right (flees~)

References

Welcome to Discuss

I've compiled a series of technical articles and materials. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, etc. in the backend of the WeChat official account "Programming Lab" to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Implementing an Admin Backend IP Whitelist with Django Middleware

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

Django数据库性能优化之使用Python集合操作

前言 最近有个新需求: 人员基础信息(记作人员A),10w 某种类型的人员信息(记作人员B),1000 要求在后台上(Django Admin)分别展示:已录入A的人员B列表、未录入的人员B列表 团队的DBA提议使用视图可以解决这个问题(不愧是搞数据库的) PS:起先我觉得Django的Model是直接管理数据库表的,使用Model来映射数据库模型怕是有一定的麻烦,不过查了一下资料发现并不会~ 只

2022-08-26 · Django · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…