To protect your web application from brute-force attacks and to keep track of and manage failed login attempts by your users, I would suggest that you either use, django-axes. I will explain how to install and set up the package.

Step 1:

To install django-axes, open your terminal and type in the following command:

pip install django-axes

Step 2:

Next, you want to add ‘axes’ under your installed apps. The position is irrelevant here, so insert it anywhere that you want.

# settings.py

INSTALLED_APPS = [
    'axes', # Axes
]

Step 3:

After this, you must add ‘axes.backends.AxesBackend’ to your authentication backends. This must be added to the top of the authentication backends list, like so:

# settings.py

AUTHENTICATION_BACKENDS = [
   'axes.backends.AxesBackend', # Axes must be first
   'django.contrib.auth.backends.ModelBackend',
]

Step 4:

# settings.py

MIDDLEWARE = [
    'axes.middleware.AxesMiddleware', # Axes 
]

Step 5:

To make sure that everything has been configured properly, give the below command a quick run:

python manage.py check

Step 6:

Now, we want to sync everything to our database, so type in the below command:

python manage.py migrate

BASIC INSTALLATION AND SETUP ARE DONE!

Step 7:

The default number of failed login attempts should be 2 or 3. Now, try it on your own and test this theory on your website. You will then see that your webpage will be locked.

To clear all the records and login attempts immediately, type the following command in your terminal:

python manage.py axes_reset

Extra information:

Some django-axes configurations that you can add to your settings.py file:

Add a failure limit:

You can modify the number of login attempts that will be allowed before a user is locked out of your application. Integers are used and the default is set to 3. I would suggest setting it to 6 or 8.

# settings.py

AXES_FAILURE_LIMIT: 6 

Set a ‘cool-off’ period:

Set your own ‘cool-off period’. This dictates how long you will have to wait before you can try logging into your website again. Integers are represented by hours and there is no default value set.

Example:

- Wait for 2 hours before logging in again

# settings.py

AXES_COOLOFF_TIME: 2 

Reset failed attempts:

If the axes-failure-limit is set to 3 failed attempts and the user logs in successfully after 2 failed attempts, we would like to reset his failed attempts to 0. To do this, we can simply set the reset on the success property to true:

# settings.py

AXES_RESET_ON_SUCCESS = True

If you need further guidance or would like to learn more about django-axes then please read the following documentation:

👉 https://django-axes.readthedocs.io/en/latest/1_requirements.html