How to Implement Two-Factor Authentication in Your Web App
Two-factor authentication (2FA) adds a second proof of identity beyond a password, blocking most account takeover attacks. This tutorial walks through a practical TOTP-based implementation you can ship in an afternoon.
You will need a backend framework, a database, and one library: otplib for Node, pyotp for Python, or rotp for Ruby.

Step 1: Choose Your 2FA Method
Time-based one-time passwords (TOTP) work with any authenticator app, cost nothing to send, and resist SIM-swap attacks. Prefer them over SMS unless accessibility requirements demand otherwise.
Step 2: Handle Enrollment
When a user enables 2FA, generate a random base32 secret, encrypt it against the user record, and render it as a QR code plus a manual text key.
- Generate the secret with
authenticator.generateSecret() - Build an
otpauth://URI with issuer and account labels - Do not activate 2FA until the user confirms one valid code
Step 3: Verify at Login
After a correct password, mark the session as “pending 2FA” and require a six-digit code. Verify with a one-step window to tolerate clock drift, then promote the session to fully authenticated.
Step 4: Prevent Lockouts and Abuse
- Generate ten single-use recovery codes and store them hashed
- Rate-limit verification attempts to about five per fifteen minutes
- Log every enable or disable event and email the user on changes
Conclusion
Start with TOTP, confirm enrollment before activation, and always ship recovery codes. A modest amount of code buys a large jump in account security.