Django with Two Factor Authentication
Reference: https://django-two-factor-auth.readthedocs.io/en/stable/
Key Concepts of 2FA with Authenticator Apps:
Something You Know (Password): The user’s primary credential
Something You Have (Authenticator App): A secondary factor, typically a mobile app (like Google Authenticator, Microsoft Authenticator, Authy) that generates time-sensitive one-time codes.
Shared Secret: A unique key exchanged between your Django application and the authenticator app during the setup process. This key is never transmitted again.
TOTP Algorithm: Both Django app and the authenticator app use this algorithm, along with the shared secret and the current time, to generate synchronized one-time codes that are valid for a short period (e.g., 30 or 60 seconds).
Step 1: Preparation, Create Django Project, Inital Migration
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==5.2 django-two-factor-auth phonenumbers
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Step 2: Project Setting myproject/settings.py
...
INSTALLED_APPS = [
...
'django_otp', # updated
'django_otp.plugins.otp_static', # updated
'django_otp.plugins.otp_totp', # updated
'django_otp.plugins.otp_email', # updated
'two_factor', # updated
'two_factor.plugins.phonenumber', # updated
'two_factor.plugins.email', # updated
]
MIDDLEWARE = [
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware', # updated
'django.contrib.messages.middleware.MessageMiddleware',
...
]
...
# updated
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
LOGIN_URL = 'two_factor:login' # updated
LOGIN_REDIRECT_URL = 'two_factor:profile' # updated
LOGOUT_REDIRECT_URL = 'two_factor:login' # updated
TWO_FACTOR_STRICT = True # updatedStep 3: Project URLs myproject/urls.py
from django.contrib import admin
from django.urls import path, include
from two_factor.urls import urlpatterns as tf_urls # updated
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(tf_urls)), #updated
]Step 4: Database Migration:
python manage.py migrate
Step 5: Create Superuser
Make migrations: python manage.py createsuperuser
Type username, email password and retype password
Step 6: Test
Run Server: python manage.py runserver
Testing: http://127.0.0.1:8000/account/login
First time login (Enable 2FA)
After 2FA enabled
