Django Two-Factor Authentication for Secure User Login
Contents
- Django Two-Factor Authentication Setup
- Basic TOTP Configuration
- Custom Authentication Backend
- User Registration with 2FA
- Custom Middleware for 2FA Enforcement
- API Token Generation with 2FA Verification
- Backup Codes Implementation
- Recovery Process Integration
- Rate Limiting and Security Measures
- SMS-Based Two-Factor Authentication
- Device Management Interface
- Security Audit Logging
- Emergency Access Protocol
- Integration Testing Suite
- Additional Resources
Django Two-Factor Authentication Setup
Django two-factor authentication enhances security by requiring users to provide additional verification beyond passwords. The django-two-factor-auth package integrates seamlessly with Django's authentication system, providing a robust foundation for implementing 2FA in web applications.
# settings.py
INSTALLED_APPS = [
'django.contrib.auth',
'django_otp',
'django_otp.plugins.otp_totp',
'django_otp.plugins.otp_static',
'two_factor',
]
MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware',
]
# Enable two-factor auth
LOGIN_URL = 'two_factor:login'
LOGIN_REDIRECT_URL = 'two_factor:profile'
Basic TOTP Configuration
Time-based One-Time Password (TOTP) implementation requires proper configuration of secret key generation and verification mechanisms. This setup establishes the foundation for generating secure temporary codes compatible with authenticator apps.
# models.py
from django_otp.plugins.otp_totp.models import TOTPDevice
from django.contrib.auth.models import User
def create_totp_device(user: User, name: str = "default"):
device = TOTPDevice.objects.create(
user=user,
name=name,
confirmed=True
)
return device.config_url
Custom Authentication Backend
A custom authentication backend enables fine-grained control over the two-factor authentication process, allowing for additional validation steps and integration with existing user management systems.
# backends.py
from django.contrib.auth.backends import ModelBackend
from django_otp import user_has_device, devices_for_user
class TwoFactorAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
user = super().authenticate(request, username=password, **kwargs)
if user and user_has_device(user):
devices = devices_for_user(user)
for device in devices:
if device.verify_token(kwargs.get('otp_token')):
return user
return None
User Registration with 2FA
The registration process must be modified to include two-factor authentication setup. This implementation guides users through device registration and initial verification while maintaining security standards.
# views.py
from django.contrib.auth.decorators import login_required
from django_otp.plugins.otp_totp.models import TOTPDevice
import qrcode
import io
@login_required
def setup_2fa(request):
if request.method == 'POST':
device = TOTPDevice.objects.create(
user=request.user,
name='default',
confirmed=False
)
# Generate QR code
qr = qrcode.QRCode(version=1, box_size=10, border=5)
qr.add_data(device.config_url)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buffer = io.BytesIO()
img.save(buffer, format='PNG')
qr_code = buffer.getvalue()
return JsonResponse({'qr_code': base64.b64encode(qr_code).decode()})
Custom Middleware for 2FA Enforcement
A specialized middleware ensures that protected routes require two-factor authentication completion, redirecting users to appropriate setup or verification pages when necessary.
# middleware.py
from django.shortcuts import redirect
from django.urls import reverse
from django_otp import user_has_device
class Require2FAMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
if not user_has_device(request.user):
if request.path != reverse('setup_2fa'):
return redirect('setup_2fa')