How to secure APIs for Registration and Login in Django Rest Framework?

后端 未结 2 976
说谎
说谎 2021-01-31 06:26

I have been and nowadays may be almost every Django Framework users using Django Rest Framework for creating REST APIs. I am using it with token authentication using django-rest

2条回答
  •  忘掉有多难
    2021-01-31 06:44

    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.

    • First to address the XSS issue -

    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.

    Implementation

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

    django.middleware.security.SecurityMiddleware
    

    Settings:

    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 -

    • Brute Force Attack

    Security Issue

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

    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.

    Implementation

    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',
        },
        ...
    }
    

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

    Hope it helps.

提交回复
热议问题