Security and hardening · Intermediate · 25 min
Add authenticator-app two-factor sign-in to a web app
By Padding · Updated 18 Nov 2026
Python 3.15.2 on python:3.15-slim · pyotp 2.12.1 · FastAPI 0.165.0
You will have a small FastAPI app that asks for a 6-digit code from an authenticator app after the password, with QR enrolment, an encrypted secret, replay and guessing protection, single-use recovery codes and a password check before 2FA can be turned off, all proven by pytest.
On this page
A password on its own fails the day it leaks. Two-factor sign-in adds a second check that a stolen password does not pass: a 6-digit code from an authenticator app on the user's phone. The app and your server share a secret, and both turn the current time into a code with the TOTP algorithm (RFC 6238). The code changes every 30 seconds and the phone needs no signal to make one.
Getting the codes to match is the easy part. Most of the work is in the edges: switching 2FA on only after the user proves their app works, keeping the shared secret useless to someone who copies your database, refusing a code that was already used, stopping guessing, and giving people a way back in when they lose their phone. You will build each of these in a small FastAPI app, and prove each one with a pytest test that controls the clock.
The app is a JSON API with cookie sessions. Passwords are hashed with Argon2id, as in Hash and verify passwords with Argon2id. Everything runs on your machine; no SMS gateway or paid service is involved.
Why an authenticator app and not SMS
Codes sent by SMS travel over the phone network, and the network is not yours. An attacker who talks a mobile operator into moving a number to a new SIM (a SIM swap) receives the codes. NIST's digital identity guidelines class SMS and voice codes as "restricted" for this reason. An authenticator app keeps the secret on the device. It also costs the user nothing per sign-in, works offline and runs on a low-end Android phone, which matters where SMS codes arrive late or not at all and data is prepaid. Across much of Africa, SMS codes are the default for banking and mobile money, so many users already know how a 6-digit code works; the app version is the same habit without the SIM risk.
TOTP still has a weakness: a convincing fake sign-in page can ask for the code and pass it on within 30 seconds. Passkeys do not have this problem, because the browser only uses a passkey on the site it was made for. If you are starting fresh and your users' devices support them, offer passkeys first and keep TOTP as a fallback; see Add passkey sign-in to a web app with WebAuthn.
Step 1 · Create the project
Make a throwaway project folder with its own virtual environment, and pin every package so the code below behaves the same for you:
mkdir -p ~/totp-demo
cd ~/totp-demo
python3 -m venv .venv
cat > requirements.txt <<'TXT'
fastapi==0.165.0
uvicorn==0.54.0
pyotp==2.12.1
segno==1.6.6
cryptography==50.0.2
argon2-cffi==25.1.0
httpx2==2.16.2
pytest==9.2.0
TXT
.venv/bin/python -m pip install --quiet -r requirements.txtWhat each one does here:
- pyotp generates secrets and computes TOTP codes.
- segno draws the QR code as SVG, with no image libraries.
- cryptography encrypts the shared secret before it is stored.
- argon2-cffi hashes passwords.
- httpx2 is what Starlette's
TestClientuses to call the app in tests; older guides installhttpxfor this, which now prints a deprecation warning.
Check it worked
.venv/bin/python -m pip freeze | grep -iE '^(pyotp|fastapi|segno)=='You see three lines: fastapi==0.165.0, PyOTP==2.12.1 (pip keeps the project's own capitals) and segno==1.6.6.
Step 2 · Encrypt the shared secret
The TOTP secret is not like a password hash. The server needs the secret itself to compute the expected code, so it cannot store a one-way hash of it. If your database leaks with plain secrets in it, the attacker can generate valid codes for every user. Encrypt each secret with a key that lives outside the database.
Generate a 256-bit key into a .env file that only you can read. The umask makes the file private as it is created:
(umask 077; .venv/bin/python -c "import base64, os; print('TOTP_ENCRYPTION_KEY=' + base64.urlsafe_b64encode(os.urandom(32)).decode())" > .env)
set -a; . ./.env; set +aThe second line loads it into your shell. Keep .env out of version control, and in production store the key in your platform's secret manager; Keep secrets out of Git covers both.
Now write crypto.py. It uses AES-GCM, which both encrypts and detects tampering:
cat > crypto.py <<'PY'
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def _key() -> AESGCM:
value = os.environ.get("TOTP_ENCRYPTION_KEY")
if not value:
raise RuntimeError("TOTP_ENCRYPTION_KEY is not set")
return AESGCM(base64.urlsafe_b64decode(value))
def encrypt_secret(secret: str, user_id: int) -> bytes:
nonce = os.urandom(12)
# The user ID is bound to the ciphertext as associated data, so a
# ciphertext copied onto another user's row will not decrypt.
sealed = _key().encrypt(nonce, secret.encode(), f"user:{user_id}".encode())
return nonce + sealed
def decrypt_secret(blob: bytes, user_id: int) -> str:
nonce, sealed = blob[:12], blob[12:]
return _key().decrypt(nonce, sealed, f"user:{user_id}".encode()).decode()
PYEach call picks a fresh random 12-byte nonce and stores it in front of the ciphertext, so the same secret never encrypts to the same bytes twice.
Check it worked
Encrypt a sample secret, decrypt it, and try to decrypt it as a different user:
.venv/bin/python - <<'PY'
import crypto
from cryptography.exceptions import InvalidTag
blob = crypto.encrypt_secret("JBSWY3DPEHPK3PXP", 1)
print("stored bytes:", len(blob), "contains secret:", b"JBSWY3DPEHPK3PXP" in blob)
print("decrypted:", crypto.decrypt_secret(blob, 1))
try:
crypto.decrypt_secret(blob, 2)
except InvalidTag:
print("another user's row: refused")
PYThe output is:
stored bytes: 44 contains secret: False
decrypted: JBSWY3DPEHPK3PXP
another user's row: refusedStep 3 · Match codes with a drift window and a replay guard
TOTP counts time in 30-second steps since 1 January 1970. The code for a step is a keyed hash of the step number, cut down to six digits. Phones and servers rarely agree on the time to the second, and a user may type a code just as it changes, so the server also accepts the step before and the step after. RFC 6238 recommends allowing no more than that.
pyotp has a verify() method with a valid_window option, but it only answers yes or no. To stop replay you need to know which step matched, so you can refuse that step, and every earlier one, next time. RFC 6238 requires this: once a code has been accepted, the same code must not be accepted again. Write otp.py:
cat > otp.py <<'PY'
import hmac
import pyotp
STEP_SECONDS = 30
DRIFT_STEPS = 1 # also accept the step before and the step after "now"
def new_secret() -> str:
return pyotp.random_base32() # 32 base32 characters, 160 bits
def provisioning_uri(secret: str, email: str, issuer: str) -> str:
return pyotp.TOTP(secret).provisioning_uri(name=email, issuer_name=issuer)
def match_step(secret: str, code: str, now: float, last_step: int) -> int | None:
"""Return the time step this code belongs to, or None if it does not match.
Steps at or below last_step were already used, so they never match again.
"""
if len(code) != 6 or not code.isdigit():
return None
totp = pyotp.TOTP(secret)
current = int(now // STEP_SECONDS)
for step in range(current - DRIFT_STEPS, current + DRIFT_STEPS + 1):
if step <= last_step:
continue
if hmac.compare_digest(totp.generate_otp(step), code):
return step
return None
PYhmac.compare_digest compares in constant time, so the response time does not leak how many digits were right. The function takes now as an argument instead of reading the clock, which lets the tests move time freely.
Write tests for it. They use a fixed moment and a fixed, made-up secret, so they give the same result every run:
cat > test_otp.py <<'PY'
import pyotp
import otp
SECRET = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" # a fixed test secret, never a real one
NOW = 1_800_000_000.0 # a fixed moment, so the test does not depend on the clock
def code_at(t: float) -> str:
return pyotp.TOTP(SECRET).at(t)
def test_current_code_matches():
assert otp.match_step(SECRET, code_at(NOW), NOW, 0) == int(NOW // 30)
def test_one_step_of_drift_either_way_is_accepted():
assert otp.match_step(SECRET, code_at(NOW - 30), NOW, 0) is not None
assert otp.match_step(SECRET, code_at(NOW + 30), NOW, 0) is not None
def test_two_steps_of_drift_is_refused():
assert otp.match_step(SECRET, code_at(NOW - 60), NOW, 0) is None
assert otp.match_step(SECRET, code_at(NOW + 60), NOW, 0) is None
def test_a_used_step_cannot_be_replayed():
step = otp.match_step(SECRET, code_at(NOW), NOW, 0)
assert otp.match_step(SECRET, code_at(NOW), NOW, step) is None
# nor can the older code from the step before it
assert otp.match_step(SECRET, code_at(NOW - 30), NOW, step) is None
def test_malformed_codes_are_refused():
for bad in ["", "12345", "1234567", "12a456", " 123456"]:
assert otp.match_step(SECRET, bad, NOW, 0) is None
PYCheck it worked
.venv/bin/python -m pytest -q test_otp.pypytest reports 5 passed. If a drift test fails on your own variation, check that you compare step numbers, not raw timestamps.
Step 4 · Build password sign-in with two kinds of session
The app needs to remember that someone got the password right but has not yet typed a code. It does this with two session stages: pending after the password, and full after the code (or straight after the password for users without 2FA). A pending session lasts five minutes and is accepted only by the code routes, so it cannot read any account data.
Write the first part of app.py. It stores users, recovery codes and sessions in SQLite, and stores only a SHA-256 hash of each session token, so a copy of the database does not hand out live sessions:
cat > app.py <<'PY'
import hashlib
import os
import secrets
import sqlite3
import time
from contextlib import contextmanager
from typing import Annotated
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import Cookie, FastAPI, HTTPException, Response
from pydantic import BaseModel
import crypto
import otp
DB_PATH = os.environ.get("DB_PATH", "app.db")
ISSUER = "Notes Demo"
PENDING_SECONDS = 5 * 60 # time allowed between password and code
SESSION_SECONDS = 12 * 60 * 60
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
totp_secret_enc BLOB,
totp_enabled INTEGER NOT NULL DEFAULT 0,
totp_last_step INTEGER NOT NULL DEFAULT 0,
totp_failures INTEGER NOT NULL DEFAULT 0,
totp_locked_until REAL NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS recovery_codes (
user_id INTEGER NOT NULL,
code_hash TEXT NOT NULL,
PRIMARY KEY (user_id, code_hash)
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
stage TEXT NOT NULL,
expires REAL NOT NULL
);
"""
hasher = PasswordHasher()
app = FastAPI()
SessionCookie = Annotated[str | None, Cookie(alias="sid")]
def now() -> float:
return time.time()
@contextmanager
def db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
try:
with conn: # commits on success, rolls back on error
yield conn
finally:
conn.close()
def init_db() -> None:
with db() as conn:
conn.executescript(SCHEMA)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def start_session(response: Response, user_id: int, stage: str) -> None:
token = secrets.token_urlsafe(32)
ttl = PENDING_SECONDS if stage == "pending" else SESSION_SECONDS
with db() as conn:
conn.execute(
"INSERT INTO sessions VALUES (?, ?, ?, ?)",
(hash_token(token), user_id, stage, now() + ttl),
)
response.set_cookie("sid", token, max_age=ttl, httponly=True, secure=True, samesite="lax")
def end_session(token: str) -> None:
with db() as conn:
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (hash_token(token),))
def current_user(sid: str | None, stage: str) -> sqlite3.Row:
if sid:
with db() as conn:
row = conn.execute(
"SELECT users.*, sessions.stage, sessions.expires FROM sessions"
" JOIN users ON users.id = sessions.user_id WHERE token_hash = ?",
(hash_token(sid),),
).fetchone()
if row and row["stage"] == stage and row["expires"] > now():
return row
raise HTTPException(401, "sign in first")
class Credentials(BaseModel):
email: str
password: str
@app.post("/signup", status_code=201)
def signup(body: Credentials):
try:
with db() as conn:
conn.execute(
"INSERT INTO users (email, password_hash) VALUES (?, ?)",
(body.email.lower(), hasher.hash(body.password)),
)
except sqlite3.IntegrityError:
raise HTTPException(409, "that email is already registered")
return {"created": True}
@app.post("/login")
def login(body: Credentials, response: Response):
with db() as conn:
user = conn.execute(
"SELECT * FROM users WHERE email = ?", (body.email.lower(),)
).fetchone()
try:
if user is None:
raise VerifyMismatchError
hasher.verify(user["password_hash"], body.password)
except VerifyMismatchError:
raise HTTPException(401, "wrong email or password")
stage = "pending" if user["totp_enabled"] else "full"
start_session(response, user["id"], stage)
return {"totp_required": bool(user["totp_enabled"])}
@app.get("/me")
def me(sid: SessionCookie = None):
user = current_user(sid, "full")
return {"email": user["email"], "totp_enabled": bool(user["totp_enabled"])}
init_db()
PYThe session cookie is HttpOnly (page scripts cannot read it), Secure (sent only over HTTPS) and SameSite=Lax. The login route answers with totp_required, so a front end knows whether to show the code box next. A real app also limits password attempts per account and per IP address; Rate limit an API in application code shows how.
The tests need a fresh database and a clock they can move. Put both in conftest.py, which pytest loads before any test file:
cat > conftest.py <<'PY'
import base64
import os
os.environ.setdefault("TOTP_ENCRYPTION_KEY", base64.urlsafe_b64encode(os.urandom(32)).decode())
os.environ["DB_PATH"] = ":memory:"
import pytest
from fastapi.testclient import TestClient
import app as app_module
class Clock:
def __init__(self):
self.t = 1_800_000_000.0
def __call__(self):
return self.t
@pytest.fixture
def clock(monkeypatch):
c = Clock()
monkeypatch.setattr(app_module, "now", c)
return c
@pytest.fixture
def client(tmp_path, monkeypatch, clock):
monkeypatch.setattr(app_module, "DB_PATH", str(tmp_path / "test.db"))
app_module.init_db()
# https, so the client sends the Secure session cookie back
return TestClient(app_module.app, base_url="https://testserver")
def sign_up_and_log_in(client, email="ada@example.com", password="correct horse battery"):
client.post("/signup", json={"email": email, "password": password})
return client.post("/login", json={"email": email, "password": password})
PY
cat > test_login.py <<'PY'
from conftest import sign_up_and_log_in
def test_password_only_login_gives_a_full_session(client):
r = sign_up_and_log_in(client)
assert r.json() == {"totp_required": False}
cookie = r.headers["set-cookie"].lower()
assert "httponly" in cookie and "secure" in cookie and "samesite=lax" in cookie
assert client.get("/me").json()["email"] == "ada@example.com"
def test_wrong_password_is_refused(client):
sign_up_and_log_in(client)
r = client.post("/login", json={"email": "ada@example.com", "password": "nope"})
assert r.status_code == 401
PYCheck it worked
.venv/bin/python -m pytest -qpytest reports 7 passed: the five code tests and the two sign-in tests.
Step 5 · Enrol with a QR code and a confirmation code
Enrolment has two calls. /2fa/setup makes a new secret, stores it encrypted and shows it as a QR code. /2fa/confirm takes a code from the app and only then switches 2FA on. Without the confirmation step, a user who scans badly, or whose phone clock is wrong, would lock themselves out on their next sign-in.
The QR code holds an otpauth://totp/... URI with the issuer, the user's email and the secret. Every mainstream authenticator app reads this format. The page also shows the secret in groups of four for anyone who cannot scan, and it is sent with Cache-Control: no-store so the browser does not keep a copy of the secret.
This part also adds the code check that every later route shares, and the recovery codes the user gets when enrolment succeeds:
- Guess limit. Six digits with one step of drift either way gives an attacker three chances in a million per guess. Unlimited guesses would get through in hours. After five wrong codes the account's code check locks for 15 minutes. That still allows about 480 guesses a day, roughly a 1 in 700 chance per day for an attacker who already has the password, so also alert the user after a lock and limit password attempts.
- Atomic replay guard. The update that records the used step only succeeds if it moves
totp_last_stepforward. If the same code arrives twice at the same moment, only one request wins. - Recovery codes. Ten random codes of 80 bits each. The server stores only a SHA-256 hash of each. A slow password hash such as Argon2id is not needed here: it protects short human-chosen passwords, and 80 random bits are far too many to guess even with a fast hash.
Append it to app.py:
cat >> app.py <<'PY'
# --- Enrolment -------------------------------------------------------------
import base64
import segno
from fastapi.responses import HTMLResponse
MAX_FAILURES = 5
LOCK_SECONDS = 15 * 60
RECOVERY_CODE_COUNT = 10
class Code(BaseModel):
code: str
def record_failure(user_id: int) -> None:
with db() as conn:
conn.execute(
"UPDATE users SET totp_failures = totp_failures + 1 WHERE id = ?", (user_id,)
)
conn.execute(
"UPDATE users SET totp_failures = 0, totp_locked_until = ?"
" WHERE id = ? AND totp_failures >= ?",
(now() + LOCK_SECONDS, user_id, MAX_FAILURES),
)
def ensure_not_locked(user: sqlite3.Row) -> None:
if user["totp_locked_until"] > now():
raise HTTPException(429, "too many wrong codes, try again later")
def check_user_code(user: sqlite3.Row, code: str) -> bool:
ensure_not_locked(user)
secret = crypto.decrypt_secret(user["totp_secret_enc"], user["id"])
step = otp.match_step(secret, code.replace(" ", ""), now(), user["totp_last_step"])
if step is not None:
with db() as conn:
# Only one request can move last_step forward, so a code sent
# twice at the same moment still works only once.
cur = conn.execute(
"UPDATE users SET totp_last_step = ?, totp_failures = 0"
" WHERE id = ? AND totp_last_step < ?",
(step, user["id"], step),
)
if cur.rowcount == 1:
return True
record_failure(user["id"])
return False
def normalise_recovery_code(code: str) -> str:
return code.upper().replace("-", "").replace(" ", "")
def hash_recovery_code(code: str) -> str:
return hashlib.sha256(normalise_recovery_code(code).encode()).hexdigest()
def issue_recovery_codes(user_id: int) -> list[str]:
codes = []
for _ in range(RECOVERY_CODE_COUNT):
raw = base64.b32encode(secrets.token_bytes(10)).decode() # 16 characters, 80 bits
codes.append("-".join(raw[i : i + 4] for i in range(0, 16, 4)))
with db() as conn:
conn.execute("DELETE FROM recovery_codes WHERE user_id = ?", (user_id,))
conn.executemany(
"INSERT INTO recovery_codes VALUES (?, ?)",
[(user_id, hash_recovery_code(c)) for c in codes],
)
return codes
@app.post("/2fa/setup", response_class=HTMLResponse)
def setup(sid: SessionCookie = None):
user = current_user(sid, "full")
if user["totp_enabled"]:
raise HTTPException(409, "two-factor sign-in is already on")
secret = otp.new_secret()
with db() as conn:
conn.execute(
"UPDATE users SET totp_secret_enc = ?, totp_last_step = 0 WHERE id = ?",
(crypto.encrypt_secret(secret, user["id"]), user["id"]),
)
uri = otp.provisioning_uri(secret, user["email"], ISSUER)
qr = segno.make(uri, error="m").svg_inline(scale=5, title="QR code for your authenticator app")
grouped = " ".join(secret[i : i + 4] for i in range(0, len(secret), 4))
html = (
"<!doctype html><title>Set up two-factor sign-in</title>"
"<h1>Scan this code with your authenticator app</h1>"
f"{qr}<p>Cannot scan it? Type this key instead: <code>{grouped}</code></p>"
"<p>Then enter the 6-digit code the app shows to finish.</p>"
)
return HTMLResponse(html, headers={"Cache-Control": "no-store"})
@app.post("/2fa/confirm")
def confirm(body: Code, sid: SessionCookie = None):
user = current_user(sid, "full")
if user["totp_enabled"] or user["totp_secret_enc"] is None:
raise HTTPException(409, "start setup first")
if not check_user_code(user, body.code):
raise HTTPException(400, "that code did not match, check the time on your phone")
with db() as conn:
conn.execute("UPDATE users SET totp_enabled = 1 WHERE id = ?", (user["id"],))
return {"enabled": True, "recovery_codes": issue_recovery_codes(user["id"])}
PYThe recovery codes are returned once, in the confirm response. Your front end should show them with a prompt to save or print them, and the server never shows them again.
Add two test helpers: one reads the key off the setup page the way a person would type it, and one computes the code an app would show at the test clock's time. Then test enrolment:
cat >> conftest.py <<'PY'
import re
import pyotp
def start_setup(client) -> str:
"""Call /2fa/setup and read the key from the page, as a person would type it."""
page = client.post("/2fa/setup").text
return re.search(r"<code>([A-Z2-7 ]+)</code>", page).group(1).replace(" ", "")
def code_for(secret: str, clock) -> str:
return pyotp.TOTP(secret).at(clock.t)
PY
cat > test_enrol.py <<'PY'
from conftest import code_for, sign_up_and_log_in, start_setup
import app as app_module
def test_setup_page_shows_a_qr_code_and_is_not_cached(client):
sign_up_and_log_in(client)
r = client.post("/2fa/setup")
assert r.status_code == 200
assert "<svg" in r.text and "<code>" in r.text
assert r.headers["cache-control"] == "no-store"
def test_secret_is_stored_encrypted(client):
sign_up_and_log_in(client)
secret = start_setup(client)
with app_module.db() as conn:
stored = conn.execute("SELECT totp_secret_enc FROM users").fetchone()[0]
assert secret.encode() not in stored
def test_2fa_stays_off_until_a_code_is_confirmed(client, clock):
sign_up_and_log_in(client)
secret = start_setup(client)
assert client.get("/me").json()["totp_enabled"] is False
assert client.post("/2fa/confirm", json={"code": "000000"}).status_code == 400
assert client.get("/me").json()["totp_enabled"] is False
r = client.post("/2fa/confirm", json={"code": code_for(secret, clock)})
assert r.status_code == 200
assert len(r.json()["recovery_codes"]) == 10
assert client.get("/me").json()["totp_enabled"] is True
PYCheck it worked
.venv/bin/python -m pytest -q test_enrol.pypytest reports 3 passed. To see the page yourself, save a setup page from a scratch database:
cat > qr_preview.py <<'PY'
from fastapi.testclient import TestClient
import app
client = TestClient(app.app, base_url="https://localhost")
login = {"email": "ada@example.com", "password": "correct horse battery"}
client.post("/signup", json=login)
client.post("/login", json=login)
page = client.post("/2fa/setup")
with open("setup.html", "w") as f:
f.write(page.text)
print(page.status_code, "wrote setup.html")
PY
DB_PATH=preview.db .venv/bin/python qr_preview.py
grep -c "<svg" setup.htmlThe script prints 200 wrote setup.html and grep prints 1. Open setup.html in a browser and scan it: your authenticator app adds an entry named Notes Demo with ada@example.com, and its 6-digit code changes every 30 seconds. The file holds a live secret, so delete it and the scratch database when you have looked:
rm setup.html preview.dbStep 6 · Ask for the code at sign-in
Add the second step of sign-in. It takes a pending session and a code, and on success replaces the pending session with a new full one. The new session ID matters: a session ID that existed before the user proved their second factor is never promoted in place.
cat >> app.py <<'PY'
# --- Second step of sign-in -----------------------------------------------
@app.post("/login/totp")
def login_totp(body: Code, response: Response, sid: SessionCookie = None):
user = current_user(sid, "pending")
if not check_user_code(user, body.code):
raise HTTPException(401, "that code did not match")
end_session(sid) # a new session ID once the user is fully signed in
start_session(response, user["id"], "full")
return {"signed_in": True}
PYAdd a helper that enrols a user and signs them out, then test the sign-in cases. Each test moves the fake clock, so drift, replay and lockout are tested without waiting:
cat >> conftest.py <<'PY'
def enrol(client, clock) -> tuple[str, list[str]]:
"""Sign up, turn 2FA on and sign out. Returns the secret and recovery codes."""
sign_up_and_log_in(client)
secret = start_setup(client)
codes = client.post("/2fa/confirm", json={"code": code_for(secret, clock)}).json()
client.cookies.clear()
clock.t += 30 # the enrolment code's step is used; move to the next one
return secret, codes["recovery_codes"]
PY
cat > test_second_factor.py <<'PY'
import pyotp
from conftest import code_for, enrol, sign_up_and_log_in
def test_password_alone_is_not_enough(client, clock):
enrol(client, clock)
r = sign_up_and_log_in(client)
assert r.json() == {"totp_required": True}
assert client.get("/me").status_code == 401
def test_password_then_code_signs_in(client, clock):
secret, _ = enrol(client, clock)
sign_up_and_log_in(client)
pending = client.cookies["sid"]
r = client.post("/login/totp", json={"code": code_for(secret, clock)})
assert r.status_code == 200
assert client.cookies["sid"] != pending # the session ID changed
assert client.get("/me").status_code == 200
def test_a_code_from_30_seconds_ago_still_works(client, clock):
secret, _ = enrol(client, clock)
sign_up_and_log_in(client)
clock.t += 30 # the phone is 30 seconds behind the server
old = pyotp.TOTP(secret).at(clock.t - 30)
assert client.post("/login/totp", json={"code": old}).status_code == 200
def test_a_code_from_90_seconds_ago_is_refused(client, clock):
secret, _ = enrol(client, clock)
sign_up_and_log_in(client)
clock.t += 90
stale = pyotp.TOTP(secret).at(clock.t - 90)
assert client.post("/login/totp", json={"code": stale}).status_code == 401
def test_a_used_code_cannot_be_replayed(client, clock):
secret, _ = enrol(client, clock)
code = code_for(secret, clock)
sign_up_and_log_in(client)
assert client.post("/login/totp", json={"code": code}).status_code == 200
# Someone who watched the code being typed tries it in another browser.
client.cookies.clear()
sign_up_and_log_in(client)
assert client.post("/login/totp", json={"code": code}).status_code == 401
def test_five_wrong_codes_lock_the_second_step(client, clock):
secret, _ = enrol(client, clock)
sign_up_and_log_in(client)
for _ in range(5):
assert client.post("/login/totp", json={"code": "000000"}).status_code == 401
right = code_for(secret, clock)
assert client.post("/login/totp", json={"code": right}).status_code == 429
clock.t += 15 * 60 + 1 # after the lock, sign in again with a fresh code
sign_up_and_log_in(client)
assert client.post("/login/totp", json={"code": code_for(secret, clock)}).status_code == 200
PYThe lockout test shows why a lock must apply to the account, not to the session: after five misses even the right code gets 429 Too Many Requests until the 15 minutes are up.
Check it worked
.venv/bin/python -m pytest -q test_second_factor.pypytest reports 6 passed. Notice the replay test: the code was still inside its 30-second window when it was tried again, and the server refused it because its step had been used.
Step 7 · Let people sign in with a recovery code
Phones get lost, stolen and reset. Without a fallback, each lost phone becomes a support ticket, and the support desk becomes the easy way into any account. A recovery code works in place of the 6-digit code, once. The route deletes the code's row as it checks it, so the same code cannot work twice even if two requests race. It counts misses towards the same lock as wrong 6-digit codes:
cat >> app.py <<'PY'
# --- Recovery codes --------------------------------------------------------
class RecoveryCode(BaseModel):
recovery_code: str
def use_recovery_code(user_id: int, code: str) -> bool:
with db() as conn:
# Deleting the row is what makes the code single-use.
cur = conn.execute(
"DELETE FROM recovery_codes WHERE user_id = ? AND code_hash = ?",
(user_id, hash_recovery_code(code)),
)
return cur.rowcount == 1
@app.post("/login/recovery")
def login_recovery(body: RecoveryCode, response: Response, sid: SessionCookie = None):
user = current_user(sid, "pending")
ensure_not_locked(user)
if not use_recovery_code(user["id"], body.recovery_code):
record_failure(user["id"])
raise HTTPException(401, "that recovery code did not match")
with db() as conn:
left = conn.execute(
"SELECT COUNT(*) FROM recovery_codes WHERE user_id = ?", (user["id"],)
).fetchone()[0]
end_session(sid)
start_session(response, user["id"], "full")
return {"signed_in": True, "recovery_codes_left": left}
PY
cat > test_recovery.py <<'PY'
import app as app_module
from conftest import enrol, sign_up_and_log_in
def test_recovery_codes_are_stored_as_hashes(client, clock):
_, codes = enrol(client, clock)
with app_module.db() as conn:
stored = [r[0] for r in conn.execute("SELECT code_hash FROM recovery_codes")]
assert len(stored) == 10
assert not any(c.replace("-", "") in "".join(stored) for c in codes)
def test_a_recovery_code_signs_in_once(client, clock):
_, codes = enrol(client, clock)
sign_up_and_log_in(client)
r = client.post("/login/recovery", json={"recovery_code": codes[0].lower()})
assert r.json() == {"signed_in": True, "recovery_codes_left": 9}
client.cookies.clear()
sign_up_and_log_in(client)
r = client.post("/login/recovery", json={"recovery_code": codes[0]})
assert r.status_code == 401
PYCodes are accepted in any case and with or without dashes, because people copy them by hand. The response says how many codes are left; show that number, and when it gets low, offer a new set (calling issue_recovery_codes again replaces the old ones). After a recovery-code sign-in, also email the user, since it is the route an attacker with a stolen code would take.
Check it worked
.venv/bin/python -m pytest -q test_recovery.pypytest reports 2 passed: the stored hashes do not contain any code, and the first code works once and is refused the second time.
Step 8 · Ask for the password and a code before 2FA is turned off
If a signed-in session is enough to switch 2FA off, then anyone who gets hold of a session, through a borrowed laptop or a stolen cookie, can remove the second factor and keep the account. Ask again for the password and a current code (or a recovery code) first. This is called step-up re-authentication. Use the same check for changing the account email or password.
cat >> app.py <<'PY'
# --- Turning two-factor sign-in off ----------------------------------------
class StepUp(BaseModel):
password: str
code: str # a 6-digit code or a recovery code
@app.post("/2fa/disable")
def disable(body: StepUp, sid: SessionCookie = None):
user = current_user(sid, "full")
if not user["totp_enabled"]:
raise HTTPException(409, "two-factor sign-in is already off")
try:
hasher.verify(user["password_hash"], body.password)
except VerifyMismatchError:
raise HTTPException(401, "enter your password again")
if len(normalise_recovery_code(body.code)) == 16:
ensure_not_locked(user)
ok = use_recovery_code(user["id"], body.code)
if not ok:
record_failure(user["id"])
else:
ok = check_user_code(user, body.code)
if not ok:
raise HTTPException(401, "that code did not match")
with db() as conn:
conn.execute(
"UPDATE users SET totp_enabled = 0, totp_secret_enc = NULL,"
" totp_last_step = 0, totp_failures = 0 WHERE id = ?",
(user["id"],),
)
conn.execute("DELETE FROM recovery_codes WHERE user_id = ?", (user["id"],))
# Sign out every other session for this user.
conn.execute(
"DELETE FROM sessions WHERE user_id = ? AND token_hash != ?",
(user["id"], hash_token(sid)),
)
return {"enabled": False}
PY
cat > test_disable.py <<'PY'
from conftest import code_for, enrol, sign_up_and_log_in
PASSWORD = "correct horse battery"
def signed_in_with_2fa(client, clock):
secret, codes = enrol(client, clock)
sign_up_and_log_in(client)
client.post("/login/totp", json={"code": code_for(secret, clock)})
clock.t += 30
return secret, codes
def test_a_signed_in_session_alone_cannot_turn_2fa_off(client, clock):
secret, _ = signed_in_with_2fa(client, clock)
r = client.post("/2fa/disable", json={"password": "guess", "code": code_for(secret, clock)})
assert r.status_code == 401
r = client.post("/2fa/disable", json={"password": PASSWORD, "code": "000000"})
assert r.status_code == 401
assert client.get("/me").json()["totp_enabled"] is True
def test_password_and_code_turn_it_off(client, clock):
secret, _ = signed_in_with_2fa(client, clock)
r = client.post("/2fa/disable", json={"password": PASSWORD, "code": code_for(secret, clock)})
assert r.json() == {"enabled": False}
assert client.get("/me").json()["totp_enabled"] is False
def test_a_recovery_code_also_works_for_step_up(client, clock):
_, codes = signed_in_with_2fa(client, clock)
r = client.post("/2fa/disable", json={"password": PASSWORD, "code": codes[3]})
assert r.json() == {"enabled": False}
PYTurning 2FA off also deletes the encrypted secret and the recovery codes, and signs out every other session. Send the user an email when it happens, so they notice if it was not them.
Check it worked
Run the whole suite:
.venv/bin/python -m pytest -qpytest reports 21 passed in a few seconds. Most of that time is Argon2id hashing passwords, which is slow on purpose.
Step 9 · Run the app and clean up
Start the app in a second terminal. Load the key first, because uvicorn reads it from the environment:
cd ~/totp-demo
set -a; . ./.env; set +a
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000uvicorn prints Uvicorn running on http://127.0.0.1:8000. Back in the first terminal, create an account and sign in:
curl -sS -X POST http://127.0.0.1:8000/signup -H 'Content-Type: application/json' \
-d '{"email": "grace@example.com", "password": "a long practice passphrase"}'
echo
curl -sS -i -X POST http://127.0.0.1:8000/login -H 'Content-Type: application/json' \
-d '{"email": "grace@example.com", "password": "a long practice passphrase"}' | tee login.txt
grep -qi '^set-cookie: sid=.*HttpOnly.*Secure' login.txt
grep -q '"totp_required":false' login.txtThe demo passwords are typed on the command line here only because they are throwaway; never do that with a real password, as it lands in your shell history.
Check it worked
The signup call prints {"created":true}. The login call prints the response headers and {"totp_required":false}, and its set-cookie line reads something like sid=...; HttpOnly; Max-Age=43200; Path=/; SameSite=lax; Secure. This account has no 2FA yet; the browser flow for it is the enrolment calls you tested above, served from a page on HTTPS so the Secure cookie is sent. Open http://127.0.0.1:8000/docs to see every route in FastAPI's interactive docs.
Stop uvicorn with Ctrl+C in the second terminal, then remove the demo folder, which also removes the key file and app.db:
cd ~
rm -rf ~/totp-demoBefore you ship this pattern, three things to add in your real app: an email to the user whenever 2FA is switched on or off or a recovery code is used, a limit on password attempts, and a way to rotate TOTP_ENCRYPTION_KEY (decrypt with the old key and re-encrypt with the new one in a one-off job).
Next steps
- Offer phishing-resistant sign-in alongside TOTP: /tutorials/add-passkey-sign-in-with-webauthn
- Check how the password step stores and verifies hashes: /tutorials/hash-passwords-with-argon2id
- Limit password and code attempts per IP address as well as per account: /tutorials/rate-limit-an-api-in-application-code
- Keep
TOTP_ENCRYPTION_KEYand other secrets out of your repository: /tutorials/keep-secrets-out-of-git
Related tutorials
- Hash and verify passwords with Argon2idYou will have a small Python password module that hashes with Argon2id at parameters tuned on your own machine, adds a pepper kept outside the database, upgrades old Argon2 and bcrypt hashes when users sign in, and produces hashes that Node.js can verify too.
- Add passkey sign-in to a web app with WebAuthnYou will have a small Express app where people create an account and sign in with a passkey instead of a password, with single-use challenges, origin and RP ID checks, stored public keys and counters, autofill sign-in, a way back in after losing a phone, and Playwright tests that run every ceremony against virtual authenticators.
- Rate limit an API in application code with a token bucketYou will give each API key its own token bucket in an Express 5.3 app, answer over-limit callers with 429, Retry-After and RateLimit headers, set different limits per plan, and share the buckets between app instances through Valkey.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials