Now a days everyone has a smartphone, this type of 2FA setup is basically now free and accessible to everyone. You can easily install a 2FA client app like Google Authenticator or Twilio Authy on your phone. Many websites also now support it and will probably become more and more common as it does improve security significantly.
On the server side, there are free and open source libraries you can use to implement these TOTP (time-based one-time password) systems. So you no longer have to pay for these expensive servers and licenses. It’s now completely accessible outside of the enterprise and you can implement it for free in your Django app.
In this post, I’ll quickly go over how you can secure your Django admin with TOTP 2FA using the django-otp package.
Step 1 : Install django-otp and qrcode for 2FA
The qrcode package is actually a optional One it is good include. it generates qrcode so that we can quickly scan with our phone to setup instead of manually typing things
pip install django-otp qrcode
Step 2 : Update your settings.py file
Add the following to your INSTALLED_APPS
INSTALLED_APPS = ( ... 'django_otp', 'django_otp.plugins.otp_totp', 'django_otp.plugins.otp_static', ... )
Add the Following in bold in MIDDLEWARE after the AuthenticationMiddleware entry :
MIDDLEWARE = ( ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ... )
# migrate our app python3 manage.py migrate
Creating a TOTP Device for 2FA
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
Now logout and login into django admin you have enter OTP everytime you need to login into django admin.