The first time I implemented two-factor auth, I copied a Stack Overflow snippet that called pyotp.verify(code) and shipped it. It worked in testing. In production, users in Japan couldn't log in for the first 30 seconds of every minute because their clock was 31 seconds ahead of ours and the verification window was strict. The fix was a one-line change. The lesson was that TOTP looks deceptively simple and has a half-dozen edge cases that bite you in production.
TOTP (Time-based One-Time Password) is what Google Authenticator, Authy, 1Password, and every "scan this QR code" prompt implement. It's standardized in RFC 6238, derived from HOTP (RFC 4226), and is the only MFA method that's free, offline, doesn't require a phone number, and works with any compliant authenticator app. It's also the one most teams implement badly.
This article is the implementation guide I wish I'd had: the math, the server-side storage, the QR code provisioning, the drift handling, the backup codes, and the production concerns that come up after you ship.
Why TOTP (and Not SMS, Email, or Push)
Before the math: which MFA method should you actually pick? They're not interchangeable.
| Method | Cost | UX | Security | Phishing resistance | Offline |
|---|---|---|---|---|---|
| SMS OTP | Per-message $ | Bad (typing 6 digits) | Weak (SIM swap, SS7) | None | No |
| Email OTP | Free | Bad (context switch) | Weak (email account takeover) | None | No |
| TOTP | Free | OK (6 digits, 30s) | Good (secret never sent) | None | Yes |
| Push (proprietary) | Per-user $ | Great (tap approve) | Good (unless user approves blindly) | None | No |
| WebAuthn / Passkey | Free | Great (biometric) | Best (origin-bound) | Yes | Yes |
| Hardware key (U2F/FIDO2) | $25-50/key | Great (tap) | Best (origin-bound, phish-proof) | Yes | Yes |
The honest stack for most apps: WebAuthn/passkeys as primary MFA, TOTP as the fallback for users who can't or won't use passkeys, backup codes for recovery. SMS only as a last resort, and only for low-risk accounts. Email OTP is barely MFA-it's "a second thing the attacker probably also controls."
TOTP's weakness is phishing. A user can be tricked into typing their TOTP code into a fake login page, and the attacker can replay it within the 30-second window. If phishing is your primary threat model (banking, exchanges, admin panels), you need WebAuthn, not TOTP. But TOTP is still the right default for most apps-it's free, it works offline, it's universally supported, and it raises the bar significantly over password-only.
Prerequisites
- Python 3.11+. The code samples use modern typing.
- A user database. I'll assume Postgres + SQLAlchemy 2.0; the patterns transfer to any DB.
-
pyotpfor TOTP math. Don't roll your own HMAC-TOTP implementation-pyotpis the de facto standard, MIT-licensed, audited, and 200 lines of code you don't have to write. -
qrcode(Python) or any QR library on the frontend. The QR encodes anotpauth://URL; you can also render it client-side with a JS library. - A way to encrypt secrets at rest. I'll use
cryptography.fernet. You need this because the TOTP secret in your DB is as sensitive as a password-if it leaks, an attacker can generate valid codes forever. - An NTP-synced server clock. TOTP is time-based; if your server drifts more than 30 seconds from the user's phone, codes won't verify. Use
chronyorsystemd-timesyncd.
How TOTP Works: the 30-Second Math
Here's the mental model. The user and the server share a secret (a 20-32 byte random key, base32-encoded). Every 30 seconds, both sides independently compute:
CodeCopy
code = HOTP(secret, counter=T / 30)
where T is Unix time in seconds and HOTP is HMAC-SHA1 truncated to 6 digits. RFC 6238 specifies the algorithm; RFC 4226 specifies HOTP. The user's phone has the secret (from scanning the QR code), the server has the secret (from the enrollment step), and the time alignment comes from NTP.
CodeCopy
plaintext
┌──────────────┐ ┌──────────────┐
│ User phone │ │ Server │
│ │ │ │
│ secret: K │ user types 6-digit │ secret: K │
│ time: T │ ─────── code ──────> │ time: T │
│ │ │ │
│ computes │ │ computes │
│ HOTP(K,T/30)│ │ HOTP(K,T/30)│
│ │ │ │
│ displays 6 │ │ compares? │
│ digits │ │ match=auth │
└──────────────┘ └──────────────┘
markdown
The secret is never transmitted during verification. The server stores it, the user's phone stores it, and only the 6-digit code crosses the wire. That's what makes TOTP secure: an attacker intercepting the code gets a value valid for at most 30 seconds (or 90 seconds with drift tolerance), and the secret stays put.
Server-Side Secret Management
The secret must be encrypted at rest. Storing it in plaintext in your DB means any DB backup leak, SQL injection, or rogue employee gives attackers the ability to generate valid codes forever. Encrypt with a key you keep in your secrets manager (Vault, AWS KMS, GCP KMS, or even an env var loaded from a sealed secret on small deployments).
PythonCopy
python
totp_service.py
import hashlib
import json
import secrets
from typing import Optional
import pyotp
from cryptography.fernet import Fernet
from sqlalchemy import Column, String, Boolean, ForeignKey
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class UserTOTP(Base):
tablename = "user_totp"
user_id = Column(ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
encrypted_secret = Column(String, nullable=True) # Fernet-encrypted base32
enabled = Column(Boolean, default=False, nullable=False)
backup_codes_hash = Column(String, nullable=True) # JSON list of SHA-256 hex
Fernet key from env, loaded once at startup.
Generate with: Fernet.generate_key()
Store in: vault / KMS / sealed-secret
fernet = Fernet(_load_fernet_key())
def generate_totp_secret() -> str:
# 32 bytes of entropy, base32 encoded (52 chars). RFC 4226 recommends >= 160 bits.
return pyotp.random_base32(length=32)
def store_totp_secret(user_id: str, secret: str) -> None:
encrypted = fernet.encrypt(secret.encode("utf-8")).decode("utf-8")
with db_session() as s:
s.execute(
"UPDATE user_totp SET encrypted_secret = :enc WHERE user_id = :uid",
{"enc": encrypted, "uid": user_id},
)
def get_totp_secret(user_id: str) -> Optional[str]:
with db_session() as s:
row = s.execute(
"SELECT encrypted_secret FROM user_totp WHERE user_id = :uid",
{"uid": user_id},
).first()
if not row or not row.encrypted_secret:
return None
return fernet.decrypt(row.encrypted_secret.encode("utf-8")).decode("utf-8")
markdown
Three things to notice. First, pyotp.random_base32(length=32) generates 32 bytes of entropy-well above the RFC minimum of 20. Second, the Fernet key is loaded once, not per-call. Third, there's no get_totp_secret endpoint that returns the secret to the user-after enrollment, the secret is write-only from the user's perspective. If they lose their phone, that's what backup codes are for.
Enrollment: Secret, QR Code, and Provisioning URI
The enrollment flow: user clicks "Enable 2FA" → server generates a secret, stores it encrypted, returns a provisioning_uri to display as a QR code → user scans with their authenticator → user types a code to confirm they have the secret → server marks TOTP as enabled=True.
The provisioning URI follows Google Authenticator's de facto format (now widely standardized):
CodeCopy
plaintext
otpauth://totp/MyApp:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&algorithm=SHA1&digits=6&period=30
plaintext
PythonCopy
python
def build_provisioning_uri(secret: str, email: str, issuer: str = "MyApp") -> str:
# pyotp builds the otpauth:// URI per the de-facto Google Authenticator spec.
return pyotp.TOTP(
secret,
digits=6,
interval=30,
digest=hashlib.sha1, # SHA1 is the RFC default; SHA256/SHA512 are optional extensions
).provisioning_uri(name=email, issuer_name=issuer)
def render_qr_png(uri: str, path: str) -> None:
import qrcode
img = qrcode.make(uri)
img.save(path)
markdown
Two important fields in the URI:
-
issuer- appears in the authenticator app next to the entry. If you skip it, some apps display "Unknown" or merge multiple accounts under one entry. Always set it to your product name. -
name- the account label. Use the user's email or username. If a user has multiple accounts on your app (rare but possible), the name disambiguates them in the authenticator.
SHA1 is the algorithm every authenticator supports. SHA256/SHA512 are optional extensions in RFC 6238 but most apps ignore them. Stick with SHA1 unless you have a specific reason-using SHA256 will silently break compatibility with Google Authenticator.
Render the QR on the server and send the PNG, or send the URI as JSON and render client-side with qrcode.js (smaller payload, lets you style the QR). I prefer client-side rendering for production because it lets you put your logo in the center of the QR without breaking scan reliability.
Verification with Drift
Here's where the first production bug bites you. The naive implementation:
PythonCopy
python
WRONG: rejects valid users whose clock is off by 1 second
def verify_code_wrong(secret: str, code: str) -> bool:
return pyotp.TOTP(secret).verify(code)
plaintext
This rejects users whose phone clock is 1-2 seconds off from your server's clock if they generate the code near a 30-second boundary. At 14:23:29, the phone computes the code for T/30 = 1724. At 14:23:31, the server computes the code for T/30 = 1725. They never match.
The fix is valid_window:
PythonCopy
python
RIGHT: accept current +/- 1 window = +/- 30s drift
def verify_code(secret: str, code: str, valid_window: int = 1) -> bool:
totp = pyotp.TOTP(secret)
return totp.verify(code, valid_window=valid_window)
plaintext
valid_window=1 means "accept the current window, the previous, and the next" - a 90-second acceptance window centered on the current 30-second window. This is the de facto standard. Google's own implementation uses the same tolerance.
Don't go higher than 1. valid_window=2 (150-second window) starts to feel like a real security degradation-a stolen code is replayable for 2.5 minutes instead of 1.5. valid_window=5 is a security disaster.
There's a second, subtler drift issue: what if your server clock is wrong? NTP should keep it within milliseconds, but container clock skew, VM migration, and broken NTP configs do happen. Monitor this. A simple check:
PythonCopy
python
def check_clock_health() -> None:
# Compare local time to a known NTP server once an hour.
# Alert if drift > 5 seconds.
import ntplib
client = ntplib.NTPClient()
try:
resp = client.request("pool.ntp.org", version=3, timeout=5)
offset = resp.offset
if abs(offset) > 5:
alert_ops(f"Server clock drift: {offset:.1f}s - TOTP verification at risk")
except Exception as e:
log.warning(f"NTP check failed: {e}")
markdown
If your server clock drifts past 30 seconds, every TOTP user gets locked out. This is a Real Thing That Happens.
Backup Codes: the Recovery Path Everyone Forgets
When a user loses their phone, they need a way back in. "Email support and we'll reset it" works but doesn't scale. The standard solution is backup codes: 8-10 one-time-use codes generated at enrollment, printed or saved by the user, used like a regular TOTP code in an emergency.
Generate them like this:
PythonCopy
python
import hashlib
import secrets
import json
def generate_backup_codes(count: int = 10) -> list[str]:
# Format: XXXX-XXXX, hex, uppercase, with a dash for readability.
# 8 hex chars = 32 bits of entropy per code - sufficient because they're one-time-use
# and the user has 10 of them.
codes = []
for _ in range(count):
raw = secrets.token_hex(4).upper() # 8 hex chars
codes.append(f"{raw[:4]}-{raw[4:]}")
return codes
def hash_backup_code(code: str) -> str:
# SHA-256 is fine here because the code has 32 bits of entropy and the
# attacker would need to find a collision for any of the user's 10 codes.
# For higher entropy codes, bcrypt/argon2 would be overkill and slow.
# Normalize: uppercase, strip whitespace before hashing.
normalized = code.upper().replace(" ", "").replace("-", "")
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
def store_backup_codes(user_id: str, codes: list[str]) -> None:
hashes = [hash_backup_code(c) for c in codes]
with db_session() as s:
s.execute(
"UPDATE user_totp SET backup_codes_hash = :h WHERE user_id = :uid",
{"h": json.dumps(hashes), "uid": user_id},
)
def verify_backup_code(user_id: str, code: str) -> bool:
with db_session() as s:
row = s.execute(
"SELECT backup_codes_hash FROM user_totp WHERE user_id = :uid FOR UPDATE",
{"uid": user_id},
).first()
if not row or not row.backup_codes_hash:
return False
hashes = json.loads(row.backup_codes_hash)
target = hash_backup_code(code)
if target not in hashes:
return False
# Remove the used code atomically.
hashes.remove(target)
with db_session() as s:
s.execute(
"UPDATE user_totp SET backup_codes_hash = :h WHERE user_id = :uid",
{"h": json.dumps(hashes), "uid": user_id},
)
return True
markdown
Three production concerns:
-
FOR UPDATElock. Without it, two simultaneous requests with the same backup code both pass verification, both remove the code, and the second one's removal fails silently because the code's already gone-or worse, both succeed and the user has used one code twice. Always lock the row. - Show codes once. Display them at enrollment, tell the user to save them somewhere safe, never show them again. If a user loses them, the recovery path is the same as losing a phone: support-assisted reset.
- Rate-limit verification attempts. A backup code has 32 bits of entropy (4 billion possibilities). At 10 codes per user, that's an effective 35-bit search space per user. With unlimited attempts, an attacker brute-forcing at 1000 req/s finds a code in ~50 days. Limit to 5 attempts per 15 minutes per account.
FastAPI Integration
Putting it all together. This is the production endpoint shape I use:
PythonCopy
python
auth_totp.py
import re
from typing import Annotated
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel, Field, EmailStr
import pyotp
from .auth import get_current_user, User, issue_jwt, get_user_by_email
from .totp_service import (
generate_totp_secret, store_totp_secret, get_totp_secret,
build_provisioning_uri, verify_code,
generate_backup_codes, store_backup_codes, verify_backup_code,
mark_totp_enabled, mark_totp_disabled,
)
from .rate_limit import rate_limit
app = FastAPI(title="Auth API")
CODE_PATTERN = r"^\d{6}$"
BACKUP_CODE_PATTERN = r"^[A-F0-9]{4}-[A-F0-9]{4}$"
class SetupResponse(BaseModel):
secret: str
provisioning_uri: str
backup_codes: list[str]
class VerifyRequest(BaseModel):
code: str = Field(..., pattern=CODE_PATTERN)
class LoginStep2Request(BaseModel):
email: EmailStr
code: str = Field(
...,
pattern=f"^({CODE_PATTERN[1:-1]}|{BACKUP_CODE_PATTERN[1:-1]})$",
)
@app.post("/auth/totp/setup", response_model=SetupResponse)
@rate_limit(key="user_id", limit=3, window=3600) # only 3 setups per hour
def setup_totp(current_user: Annotated[User, Depends(get_current_user)]):
# Don't allow re-setup if already enabled - forces disable flow first.
if current_user.totp_enabled:
raise HTTPException(400, "TOTP already enabled. Disable first to re-enroll.")
secret = generate_totp_secret()
store_totp_secret(current_user.id, secret)
codes = generate_backup_codes()
store_backup_codes(current_user.id, codes)
uri = build_provisioning_uri(secret, current_user.email)
return SetupResponse(secret=secret, provisioning_uri=uri, backup_codes=codes)
@app.post("/auth/totp/verify")
@rate_limit(key="user_id", limit=10, window=600) # 10 attempts per 10 min
def verify_setup(
current_user: Annotated[User, Depends(get_current_user)],
req: VerifyRequest,
):
secret = get_totp_secret(current_user.id)
if not secret:
raise HTTPException(400, "TOTP not set up. Call /setup first.")
if current_user.totp_enabled:
raise HTTPException(400, "TOTP already enabled.")
if not verify_code(secret, req.code):
raise HTTPException(400, "Invalid code. Check your authenticator time sync.")
mark_totp_enabled(current_user.id)
return {"enabled": True}
@app.post("/auth/totp/disable")
def disable_totp(
current_user: Annotated[User, Depends(get_current_user)],
req: VerifyRequest,
):
# Require a valid TOTP code to disable - prevents session hijack from
# silently turning off 2FA.
secret = get_totp_secret(current_user.id)
if not secret or not current_user.totp_enabled:
raise HTTPException(400, "TOTP not enabled.")
if not verify_code(secret, req.code):
raise HTTPException(400, "Invalid code.")
mark_totp_disabled(current_user.id)
return {"enabled": False}
@app.post("/auth/login/2fa")
@rate_limit(key="email", limit=5, window=900) # 5 attempts per 15 min per email
def login_step2(req: LoginStep2Request):
user = get_user_by_email(req.email)
# Don't reveal whether the email exists - return the same error either way.
if not user or not user.totp_enabled:
raise HTTPException(400, "Invalid credentials.")
if req.code.isdigit():
secret = get_totp_secret(user.id)
ok = secret is not None and verify_code(secret, req.code)
else:
ok = verify_backup_code(user.id, req.code.upper())
if not ok:
raise HTTPException(400, "Invalid code.")
return {"access_token": issue_jwt(user), "token_type": "bearer"}
markdown
The /auth/login/2fa endpoint accepts both 6-digit TOTP codes and XXXX-XXXX backup codes via the same path. The frontend detects which the user typed (regex on input) and submits. Users don't care about the distinction; they care that they can log in.
The @rate_limit decorators are critical. Without them, an attacker can brute-force codes at the speed of your API. With 6-digit codes, 1 million possibilities, and a 90-second verification window (with drift), unlimited attempts at 1000 req/s find a code in 1000 seconds. Limit to 5 attempts per 15 minutes per account and the same attack takes 28 days-enough time for the user to notice.
Frontend: QR Code, Deep Link, and Manual Entry
The backend returns provisioning_uri and the secret string. The frontend does three things:
- Render the QR code from
provisioning_uri(so the user can scan it with their phone's camera). - Display the secret as text (so the user can type it into an authenticator that doesn't have camera access, e.g., a desktop password manager).
- Show a 6-digit input and submit to
/auth/totp/verify.
TypeScriptCopy
tsx
// TOTPSetup.tsx
import { useState } from "react";
import QRCode from "qrcode";
export function TOTPSetup({ userEmail }: { userEmail: string }) {
const [qrUrl, setQrUrl] = useState("");
const [secret, setSecret] = useState("");
const [code, setCode] = useState("");
const [status, setStatus] = useState<"idle" | "verifying" | "done" | "error">("idle");
async function startSetup() {
const res = await fetch("/auth/totp/setup", { method: "POST", credentials: "include" });
const data = await res.json();
setSecret(data.secret);
const url = await QRCode.toDataURL(data.provisioning_uri, { width: 240, margin: 1 });
setQrUrl(url);
}
async function verify() {
setStatus("verifying");
const res = await fetch("/auth/totp/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ code }),
});
if (res.ok) {
setStatus("done");
alert("Save your backup codes! You won't see them again.");
} else {
setStatus("error");
}
}
// render: <img src={qrUrl} /> + secret + 6-digit input + verify button
}
markdown
Two UX details that matter:
-
Always provide manual entry. Some users use 1Password, KeePass, or a YubiKey Authenticator that doesn't scan QR codes. Show the secret as a formatted string (
JBSW Y3DP EHPK 3PXP) with a copy button. -
Test with multiple authenticators. Google Authenticator, Microsoft Authenticator, Authy, 1Password, and the FOSS Aegis all have small quirks. Microsoft Authenticator sometimes ignores the
algorithm=SHA1parameter and uses SHA256 by default-if your server uses SHA1, codes don't match. Stick with the defaults (SHA1, 6 digits, 30s) and you'll be compatible with everything.
Don't try to be clever with deep links (otpauth:// URLs that directly open an authenticator). They don't work reliably across platforms-iOS Safari treats them as unknown schemes, Android shows a "open with..." dialog. QR codes are the universal interface.
Production Considerations
Encrypt the secret at rest. This is non-negotiable. The TOTP secret is a credential. If your DB leaks, attackers can generate valid codes for every user. Use Fernet, AES-GCM, or your cloud KMS-anything with authenticated encryption. Don't use raw AES-CBC.
Rotate the encryption key. Generate a new Fernet key, decrypt with old, re-encrypt with new, store both keys during the rotation period. Fernet supports this natively via MultiFernet. Schedule this yearly.
Rate-limit everything. /auth/login/2fa is the highest-risk endpoint-brute-force target. 5 attempts per 15 minutes per account is the floor. Consider 3 per 5 minutes for high-security apps. Use a sliding window with Redis, not a fixed window, so attackers can't reset their quota by waiting for the window boundary.
Lock out repeated failures. After 10 failed attempts in an hour, lock the account for 30 minutes and email the user. This is your defense against distributed brute-force (multiple IPs trying the same account).
Don't log codes. Logs are often stored unencrypted, accessible to ops, and shipped to third-party observability tools. A 6-digit code in a log file is a 30-second-valid credential. Sanitize request bodies before logging, or never log the verification endpoint's request body.
Handle clock skew. Already covered-valid_window=1. Also monitor your server's NTP sync.
Plan for the recovery flow. Users will lose their phone and their backup codes. Define the manual recovery path: identity verification (e.g., government ID + selfie, or a notarized form), then a forced TOTP reset. Document this. Decide the threshold (e.g., $100 in account value = email reset, $10,000 = ID verification).
Rotate secrets on suspicion. If you suspect a credential leak, force-reset every user's TOTP secret at next login. Don't try to rotate silently-users will be confused when their authenticator stops working.
Common Mistakes
Storing secrets in plaintext. I've seen this in production at three different companies. The justification is always "the DB is behind a VPC." The DB backup isn't. The read replica isn't. The DBA's laptop isn't. Encrypt.
Using valid_window=0. Saves you nothing security-wise (the code is still replayable for 30 seconds either way) and breaks users with even 1 second of clock skew. Always allow at least +/- 1 window.
Not showing backup codes at enrollment. "We'll add them later." You won't. Users will lose their phones. You'll spend a week building a manual reset flow under pressure. Add backup codes on day one.
Letting users disable 2FA without a code. If session hijack is in your threat model (and it should be), the disable endpoint must require a valid TOTP code. Otherwise, an attacker with a stolen session cookie silently turns off 2FA and changes the password.
Revealing whether the email exists. The /auth/login/2fa endpoint must return the same error for "email doesn't exist" and "wrong code." Otherwise, attackers enumerate accounts by trying valid codes against non-existent emails and getting "user not found" instead of "invalid code."
Logging the code. Already covered. Don't.
Using SHA256 instead of SHA1. Sounds more secure. Breaks Google Authenticator. Use SHA1, the RFC 6238 default.
Not testing with real authenticators. "It works with pyotp, ship it." Then a user with Microsoft Authenticator can't log in because MS auth uses a different default algorithm. Test with at least 3 apps before shipping.
Troubleshooting
"User can't log in, code is always wrong." First, check the server clock: timedatectl status or date -u. Drift > 5s is suspicious; > 30s explains everything. Second, check the user's phone clock-if they're in a different timezone, the phone should auto-sync via NITZ (cellular) or NTP (WiFi). Manual time entry on the phone breaks TOTP. Third, verify the secret matches: have the user read the secret from their authenticator (most apps show it) and compare to the DB.
"Codes work intermittently." The user's phone clock is drifting or the server is. Check NTP on the server. If the user is on a phone with manual time set, tell them to switch to automatic.
"User scanned QR, code is wrong." The QR is malformed. Verify the otpauth:// URI is correctly formatted: otpauth://totp/Issuer:account?secret=BASE32&issuer=Issuer&digits=6&period=30&algorithm=SHA1. Common bug: URL-encoding the email (alice%40example.com) breaks some authenticators. Use the raw email.
"Backup codes don't work." Two common causes. Hash mismatch-did you normalize before hashing (uppercase, strip dashes/spaces)? Or the code was already used-FOR UPDATE lock wasn't held during verify, so a duplicate request consumed the code before the user's request did.
"Disabled TOTP, can't re-enable." Stale state. The enabled flag was reset but encrypted_secret wasn't cleared, so the new enrollment stored a new secret but the verification step still tries to verify against the old one. Always clear encrypted_secret when disabling.
"User lost phone AND backup codes." Manual recovery flow. Verify identity (your call), reset encrypted_secret and backup_codes_hash to NULL, set enabled=False, force password reset. Email the user a confirmation. Document the incident.
"Brute-force alerts firing." Good. The rate limiter is working. Review the IPs-if they're from one country and the user is elsewhere, the account is under attack. Lock the account, email the user, require password reset.
"TOTP works locally, fails in production." Production is in a different timezone. TOTP is timezone-independent (uses Unix time), so this shouldn't matter-unless your server's TZ is set wrong and an NTP sync is correcting it abruptly. Run timedatectl and confirm NTP=active.
Testing
Unit-test the math:
PythonCopy
python
import time
import pyotp
import pytest
from myapp.totp_service import (
generate_totp_secret, verify_code, build_provisioning_uri,
)
def test_secret_is_base32():
secret = generate_totp_secret()
assert set(secret) <= set("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
assert len(secret) == 52 # 32 bytes base32-encoded
def test_verify_current_code():
secret = pyotp.random_base32()
code = pyotp.TOTP(secret).now()
assert verify_code(secret, code) is True
def test_verify_previous_window_accepted():
secret = pyotp.random_base32()
# Code from 30 seconds ago
old_code = pyotp.TOTP(secret).at(time.time() - 30)
assert verify_code(secret, old_code) is True # valid_window=1
def test_verify_old_code_rejected():
secret = pyotp.random_base32()
old_code = pyotp.TOTP(secret).at(time.time() - 90)
assert verify_code(secret, old_code) is False # outside +/- 1 window
def test_provisioning_uri_format():
secret = "JBSWY3DPEHPK3PXP"
uri = build_provisioning_uri(secret, "alice@example.com", "MyApp")
assert uri.startswith("otpauth://totp/MyApp:alice@example.com?")
assert "secret=JBSWY3DPEHPK3PXP" in uri
assert "issuer=MyApp" in uri
plaintext
Integration-test the endpoints:
PythonCopy
python
def test_setup_then_verify_flow(client, auth_token):
# Setup
r = client.post("/auth/totp/setup", headers={"Authorization": f"Bearer {auth_token}"})
assert r.status_code == 200
secret = r.json()["secret"]
backup_codes = r.json()["backup_codes"]
assert len(backup_codes) == 10
# Verify with current code
code = pyotp.TOTP(secret).now()
r = client.post("/auth/totp/verify",
headers={"Authorization": f"Bearer {auth_token}"},
json={"code": code})
assert r.status_code == 200
# Login with 2FA - need a fresh code, the previous one is consumed by time
new_code = pyotp.TOTP(secret).now()
r = client.post("/auth/login/2fa",
json={"email": "test@example.com", "code": new_code})
assert r.status_code == 200
assert "access_token" in r.json()
# Backup code works
r = client.post("/auth/login/2fa",
json={"email": "test@example.com", "code": backup_codes[0]})
assert r.status_code == 200
# Backup code can't be reused
r = client.post("/auth/login/2fa",
json={"email": "test@example.com", "code": backup_codes[0]})
assert r.status_code == 400
plaintext
Test the rate limit:
PythonCopy
python
def test_login_rate_limit(client):
for _ in range(5):
r = client.post("/auth/login/2fa",
json={"email": "victim@example.com", "code": "000000"})
assert r.status_code == 400
# 6th attempt: rate limited
r = client.post("/auth/login/2fa",
json={"email": "victim@example.com", "code": "000000"})
assert r.status_code == 429
Cost Considerations and Alternatives
TOTP is free at runtime-you run the math on your own server, no per-user or per-message cost. The real costs:
- Engineering time: 2-3 days to implement correctly end-to-end, including backup codes, rate limiting, recovery flow, and tests.
- Support load: users will lose phones. Plan for ~0.5% of users/month needing manual reset. At 10k users, that's 50 support tickets/month.
- Monitoring: clock-drift alerts, brute-force alerts, enrollment drop-off tracking.
| Alternative | Cost | When to choose |
|---|---|---|
| Auth0 / Okta | $0.02-0.13/MAU | You don't want to own auth at all; small team, big auth surface |
| Clerk | $0.02/MAU, free up to 10k | Modern UX, drop-in components, you pay for the components |
| AWS Cognito | $0.0055/MAU | All-AWS shop, basic needs |
| Supabase Auth | Free up to 50k MAU | Already on Supabase |
| Custom TOTP (this article) | Engineering time only | You want full control, low cost at scale, custom UX |
For most teams under 50k users, buying auth (Clerk/Auth0) costs more than building TOTP but saves you the support load. The break-even is around 5k-10k users depending on your engineering rates. Above 50k users, custom TOTP is significantly cheaper and you have control over the UX, the recovery flow, and the data.
The other consideration: passkeys are coming. WebAuthn support in browsers and OSes is now universal. In 2-3 years, TOTP will be the legacy fallback for users who haven't migrated to passkeys. Plan your implementation so that adding passkey support later is a parallel path, not a rewrite. The /auth/login/2fa endpoint should accept WebAuthn assertions alongside TOTP codes.
Real-World Use Cases
The fintech compliance path. A neobank needs 2FA for transactions over $1000. SMS was the original plan; SIM-swap attacks made it unacceptable. TOTP rolled out in two weeks, with backup codes for recovery. Passkeys are on the roadmap for next year.
The open-source self-hosted app. A GitLab competitor needs 2FA but can't ship a SaaS auth provider. TOTP is implemented natively, requires no external service, and works in air-gapped deployments. Authy's "cloud sync" feature is explicitly not used-the whole point is that secrets stay on the user's device.
The SaaS admin panel. A B2B SaaS company offers TOTP as the default MFA for admin users, with SSO (SAML) as an alternative for enterprise customers. TOTP is the fallback when SSO is down or for users not yet provisioned in the IdP.
The legacy migration. A bank has 5 million users with SMS OTP. They roll out TOTP as an optional upgrade, offering it during login ("Want to switch to an app-based code?"). 30% of users migrate in the first year. SMS remains for users who don't want to install an app. The bank saves $200k/year in SMS fees.
Conclusion
TOTP looks like a 50-line feature and ships as a 500-line feature with a recovery flow, a rate limiter, an encryption layer, and a monitoring dashboard. The math is simple. The production concerns aren't. Get the math right (use pyotp, allow valid_window=1), get the storage right (encrypt at rest, rotate keys), get the recovery right (backup codes, manual reset flow), and get the rate limiting right (5 attempts per 15 minutes per account). Do those four and you've built TOTP the way it should be built-not the way the Stack Overflow snippet suggested.
The next step after TOTP is passkeys. WebAuthn is the right long-term answer-it's phishing-resistant, doesn't require a 6-digit code, and works with biometrics. But TOTP is the right now answer for the next 2-3 years while passkey adoption matures. Build TOTP correctly today, leave room for passkeys tomorrow.
Originally published on Mango Developer.
Top comments (0)