How to protect API for registration and login to Django Rest Framework?

I was and can now be almost every Django Framework user using the Django Rest Framework to create a REST API. I use it with token authentication using django-rest-framework-jwt , and it returns the token when the User logs in through our leisure API.

So the question is how to provide registration or login for our API endpoints. Any high-level XSS scenario can have a malicious cycle to create registrations. How can we protect it in the Django Rest Framework?

+6
source share
1 answer

As you said, you cannot use an authentication system such as JWT to protect your pages, such as login and registration. However, there are many other things you can do. Below I mentioned two of them briefly, so that you start and relax, you can study in detail.

  • First, to solve the XSS problem -

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 the page. If JavaScript is reproduced in the server response, the page is blocked from rendering, and an error page is displayed 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 the script from hitting your login or registration pages several times are

  • Brute force attack

Security issue

An automated program can attack to crack a username and password of a user or slow down a server.

These attacks usually take one of several forms: 1. A single IP address that attempts to use a single username with a large number of passwords. 2. Many IP addresses try to use the same username with a lot of passwords. 3. One IP address that tries to use many usernames with multiple public passwords. 4. Many IP addresses try to use many usernames with one or more public passwords. 5. Attack on any random domain URL to slow down server response.

Implementation

Django Rest Framework provides built-in throttling settings

 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 to prevent only failed login attempts.

Hope this helps.

+4
source

All Articles