How It Works
TOTP generates six-digit codes that change every 30 seconds based on:- A shared secret key stored in your database
- The current time
- The HMAC-SHA1 algorithm
- A random secret is generated
- The secret is encoded as a QR code
- User scans the QR code with their authenticator app
- User enters a code from their app to verify setup
- The secret is encrypted and stored in the database
Configuration
TOTP is enabled by default. Configure it insettings.py:
settings.py
Settings Reference
MFA_TOTP_PERIOD
Default: 30
The number of seconds a TOTP code remains valid.
MFA_TOTP_DIGITS
Default: 6
The number of digits in generated codes. Most authenticator apps support 6 or 8 digits.
MFA_TOTP_ISSUER
Default: "" (uses site name)
The issuer name displayed in authenticator apps. Helps users identify which account the code is for.
MFA_TOTP_TOLERANCE
Default: 0
Number of time periods (past and future) to accept. Helps with clock drift between server and client.
URL Endpoints
TOTP URLs are available at:/accounts/mfa/totp/activate/- Activate TOTP authentication/accounts/mfa/totp/deactivate/- Deactivate TOTP authentication
Activation Flow
Users can activate TOTP through theActivateTOTPView:
Template Context
The activation template receives:Custom Template Example
templates/mfa/totp/activate_form.html
Programmatic Usage
Generate and Validate Codes
Activate TOTP for a User
Check if User Has TOTP Enabled
Validate TOTP During Login
Customizing Forms
Override the default forms insettings.py:
settings.py
Custom Activation Form
myapp/forms.py
Customizing the TOTP URL
Override the adapter to customize QR code generation:myapp/adapter.py
settings.py
Security Considerations
Secret Storage
TOTP secrets are stored encrypted in the database:Code Reuse Prevention
TOTP codes are cached after use to prevent replay attacks:Development & Testing
Bypass Code for Testing
settings.py
123456 as a valid code during testing, regardless of the actual TOTP value.
Recovery Codes
When users activate TOTP, recovery codes are automatically generated. This ensures users can access their account if they lose their authenticator device. Learn more about recovery codes →Common Issues
Clock Drift
If users report codes not working:QR Code Not Displaying
Ensureqrcode is installed:
Codes Not Accepted
Check thatdjango.contrib.messages is installed and configured:
Related
- Recovery Codes - Backup codes for account recovery
- WebAuthn - Hardware key authentication
- Configuration - All MFA settings
