如何使用Django Rest节流防止Django Rest+中的暴力攻击

2024-06-28 11:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在特定时间内阻止特定用户使用Django REST节流。

我见过Django REST Throttling。在

我不想使用第三方软件包。在

提前谢谢


Tags: django用户rest时间节流throttling
1条回答
网友
1楼 · 发布于 2024-06-28 11:15:40

我在定制Django REST节流后找到了解决方案

它在3次登录尝试后阻止特定用户(阻止我的应用程序中显示的用户_id)。 在匿名用户尝试6次登录后阻止IP地址。在

防止.py:-

#!/usr/bin/python

from collections import Counter

from rest_framework.throttling import SimpleRateThrottle
from django.contrib.auth.models import User


class UserLoginRateThrottle(SimpleRateThrottle):
    scope = 'loginAttempts'

    def get_cache_key(self, request, view):
        user = User.objects.filter(username=request.data.get('username'))
        ident = user[0].pk if user else self.get_ident(request)

        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }

    def allow_request(self, request, view):
        """
        Implement the check to see if the request should be throttled.
        On success calls `throttle_success`.
        On failure calls `throttle_failure`.
        """
        if self.rate is None:
            return True

        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True

        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()

        if len(self.history) >= self.num_requests:
            return self.throttle_failure()

        if len(self.history) >= 3:
            data = Counter(self.history)
            for key, value in data.items():
                if value == 2:
                    return self.throttle_failure()
        return self.throttle_success(request)

    def throttle_success(self, request):
        """
        Inserts the current request's timestamp along with the key
        into the cache.
        """
        user = User.objects.filter(username=request.data.get('username'))
        if user:
            self.history.insert(0, user[0].id)
        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True

视图.py:-

^{pr2}$

在设置文件中添加一些参数

设置.py:-

# Django-rest-framework
REST_FRAMEWORK = {
    ...
    ...
    ...
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.UserRateThrottle',

    ),
    'DEFAULT_THROTTLE_RATES': {
        'loginAttempts': '6/hr',
        'user': '1000/min',
    }
}

相关问题 更多 >