曦远 (DealiAxy)一份私人的文字刊物

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-Q轻度体验

前言 最近做的这个项目(基于Django),需要做个功能,实现定时采集车辆定位。 这让我想起来几年前那个OneCat项目,当时我用的是Celery这个很重的组件 Celery实在是太重了,后来我做公众号采集平台的时候,又接触了Django-RQ和Django-Q这俩,前者是对RQ的封装,让RQ和Django更好的结合在一起;后者是一个全新的「多进程任务队列」组件,相比起celery很轻量,当时使用

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

讨论

共 0 条

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

加载评论中…