Overview
Multi-factor authentication (MFA) adds another proof of identity beyond a password. A common option for web applications is TOTP, where an authenticator app generates short-lived codes from a shared secret and the current time.
Enrollment flow
Generate a cryptographically random secret for the account and show it once as a QR code or manual setup key. Do not activate MFA immediately. Ask the user to enter a valid code first; this confirms that their authenticator is configured correctly.
Verify codes safely
Use a maintained TOTP library that follows the relevant standard rather than implementing the algorithm from scratch. Allow only a small clock-drift window. Rate-limit attempts and record the last accepted time step if your library and design support replay prevention.
Protect the secret
Encrypt TOTP secrets at rest with a key stored outside the database and web root. Restrict access to the decryption key. Never include secrets in application logs, analytics or support messages.
Recovery codes
Generate several one-time recovery codes using a cryptographically secure random generator. Store only password-style hashes of those codes. Each code must be invalidated after use. Explain how users can replace lost authenticators through a verified recovery process.
Session and account changes
After successful MFA, regenerate the session ID and record the authentication strength and time. Require reauthentication for disabling MFA, changing recovery methods or other sensitive account actions. Notify users when MFA settings change.
Checklist
- Use a maintained TOTP implementation.
- Confirm enrollment with a valid code.
- Encrypt stored shared secrets.
- Rate-limit verification attempts.
- Hash and invalidate recovery codes.
- Regenerate sessions after authentication.
- Require reauthentication for security changes.
References
RFC 6238 TOTP · OWASP Multifactor Authentication Cheat Sheet