How to implement two-factor authentication in a web app

· Category: Cybersecurity

Short answer

Two-factor authentication (2FA) requires users to provide a second proof of identity beyond their password — typically a time-based one-time password (TOTP) from an authenticator app. You generate a shared secret, store its hash, show the user a QR code to scan, and verify their TOTP codes on login. For the difference between authentication and authorization, see authentication vs authorization.

Implementation steps

  1. Generate a secret: Create a random base32 string (20+ bytes) for each user
  2. Store hashed: Never store the plaintext secret — hash it like a password. See how does hashing work for hashing best practices
  3. Generate QR code: Encode the secret as an otpauth://totp/ URI and display as a QR code
  4. User scans with authenticator: Google Authenticator, Authy, or any TOTP app
  5. Verify on login: User enters 6-digit code; server computes the expected code and compares

Code example (Python)

import pyotp
import qrcode

secret = pyotp.random_base32()
uri = pyotp.totp.TOTP(secret).provisioning_uri(
    name="[email protected]", issuer_name="MyApp"
)
qr = qrcode.make(uri)
qr.save("qr.png")

# Verify
totp = pyotp.TOTP(secret)
is_valid = totp.verify(user_code)

Tips

  • Allow backup codes for users who lose their authenticator device
  • Rate-limit verification attempts to prevent brute force (6-digit codes = 1M possibilities)
  • Consider WebAuthn/FIDO2 as a modern alternative that doesn't require secrets