Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django
Setup 2 Factor Authentication for Django Project
We will install TOTP package for our blog CMS which will add OTP security for our admin login. First install django-otp package
pip install django-otp
and add 'django_otp, django_otp.plugins.otp_totp' in our installed apps and django_otp.middleware.OTPMiddleware in middleware section of our settings file.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_otp',
'django_otp.plugins.otp_totp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_otp.middleware.OTPMiddleware'
]
Now run,
# migrate our app python3 manage.py migrate
Creating a TOTP Device -
Now log into django admin to create an TOTP device. You can see it after logging in

Click add and fill the details to create a new TOTP qrcode

Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps.

Set Admin OTP Class -
Now go into django urls.py file in gfgblog, not in blog urls.py and add the lines
from django_otp.admin import OTPAdminSite
admin.site.__class__ = OTPAdminSite
Output -
Now logout and login into django admin you have enter OTP everytime you need to login into django admin.

Some Basic Security Principles to follow
- Keep Debug = False in Production
- Limit Allowed hosted to our Server IP, localhost, and hostnames
- Keep Secret key strong and safe
- All ways use HTTPS in Production
- Keep a check on user uploads if being managed by multiple users
- Keep your database secure and don't use SQLite in Production
- Try to use Security and content headers in production, a few headers are given below add these in Settings.py
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
CSRF_COOKIE_SECURE = True