Securing Django Admin login with OTP (2 Factor Authentication)
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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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.
# 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
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