且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Django Rest Framework 中保护用于注册和登录的 API?

更新时间:2022-02-06 23:23:40

正如您所说,您不能拥有像 JWT 这样的身份验证系统来保护您的页面,例如登录和注册.但是,您还可以做许多其他事情.下面我简单地提到了其中的两个,以帮助您入门,休息您可以详细学习.

As you have stated, you cannot have an authentication system like JWT protect your pages like login and registration. However there are many other things you can do. Below I have mentioned two of them briefly to get you started and rest you can study in detail.

  • 首先解决 XSS 问题 -

某些浏览器能够阻止似乎是 XSS 攻击的内容.它们通过在页面的 GET 或 POST 参数中查找 JavaScript 内容来工作.如果 JavaScript 在服务器的响应中被重放,页面将被阻止呈现并显示错误页面.X-XSS-Protection 头用于控制 XSS 过滤器的操作.

Some browsers have the ability to block content that appears to be an XSS attack. They work by looking for JavaScript content in the GET or POST parameters of a page. If the JavaScript is replayed in the server’s response, the page is blocked from rendering and an error page is shown instead. The X-XSS-Protection header is used to control the operation of the XSS filter.

实施

Django 提供在 settings>base.py 中添加的中间件和设置中间件:

Django provides middleware and settings added in settings>base.py Middleware:

django.middleware.security.SecurityMiddleware

设置:

SECURE_BROWSER_XSS_FILTER = True
This sets header to X-XSS-Protection: 1; mode=block

为了防止某些脚本重复访问您的登录或注册页面,您可以采取的其他措施是 -

Other things you can do to prevent some script from hitting your login or registration pages repeatedly is -

  • 蛮力攻击

安全问题

自动化程序可能会攻击以破解用户的用户名和密码或降低服务器速度.

An automated programme may attack to hack username and password of a user or to slow down the server.

这些攻击通常采用以下几种形式之一:1. 一个 IP 地址尝试一个用户名和多个密码.2. 许多 IP 地址尝试使用一个用户名和多个密码.3. 一个IP地址尝试多个用户名和几个常用密码.4. 许多 IP 地址使用一个或几个常用密码尝试多个用户名.5. 攻击域内任意随机url,降低服务器响应速度.

These attacks generally take one of a few forms: 1. One IP address trying one username with many passwords. 2. Many IP addresses trying one username with many passwords. 3. One IP address trying many usernames with a few common passwords. 4. Many IP addresses trying many usernames with one or a few common passwords. 5. Attacking on any random url on domain to slow down the server response.

实施

Django Rest Framework 提供内置的节流设置

Django Rest Framework provides inbuilt settings for throttling

REST_FRAMEWORK = {
    ...
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
        'rest_framework.throttling.ScopedRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '60/minute',
        'app1': '10000/day',
        'app2': '10000/day',
    },
    ...
}

另一种解决方案是 django-defender 或 django-ratelimit,用于仅防止失败的登录尝试.

Another solution is django-defender or django-ratelimit for preventing only for failed login attempts.

希望有帮助.