Two-Factor Authentication in Python with pyotp: TOTP, QR Codes and FastAPI (2026)

Web Development Nov 15, 2026

Watch on YouTube

A strong password is no longer enough. Passwords get phished, reused and leaked, and the cheapest way to stop a stolen password from becoming a stolen account is a second factor: the six-digit code from an authenticator app such as Google Authenticator, Microsoft Authenticator, Authy or 1Password. Those codes are TOTP (Time-based One-Time Passwords, RFC 6238), and in Python you generate and check them with pyotp. pyotp 2.11 (November 2026) added verify_and_get_timecode(), which finally makes it easy to block a code from being used twice. In this guide we create secrets, show the QR code users scan, verify codes with clock-drift tolerance, add replay protection and one-time backup codes, and wire everything into a FastAPI login. Everything was tested on Python 3.13.5 with pyotp 2.11.1, qrcode 8.2, FastAPI 0.163.0 and argon2-cffi 25.1.0, and every output block is the real output of the script above it. Secrets and live codes are random, so yours will differ.

How TOTP works in one paragraph

When a user turns on 2FA, the server creates a random shared secret and shows it as a QR code. The authenticator app stores it. From then on, both sides compute HMAC-SHA1(secret, floor(unix_time / 30)) and shorten it to six digits. Nothing is sent over the network: the phone and the server simply agree because they share the secret and the clock. That is why TOTP works offline, and why the secret must be kept as carefully as a password. The number floor(unix_time / 30) is called the timecode; it changes every 30 seconds, and it is the key to replay protection later on.

Install

python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install pyotp "qrcode[pil]" fastapi httpx2 argon2-cffi
pip show pyotp                 # 2.11.0 or newer for verify_and_get_timecode()

pyotp is pure Python with no dependencies. qrcode needs Pillow to write PNG files. FastAPI, argon2-cffi and httpx2 (the test client backend that Starlette now recommends instead of httpx) are only needed for the last section.

Step 1: Create a secret and verify codes

pyotp.random_base32() returns a 32-character base32 secret, which is 160 bits, the length RFC 4226 recommends. TOTP(secret) uses the defaults every authenticator app expects: SHA-1, six digits and a 30-second interval. The first half of the script uses the real clock; the second half pins the clock with at() and for_time so the result is repeatable:

import time
import pyotp

# 1) One secret per user, created at enrolment and stored server-side
secret = pyotp.random_base32()            # 32 base32 chars = 160 bits
print("New secret:", secret, f"({len(secret)} chars)")

totp = pyotp.TOTP(secret)                 # SHA-1, 6 digits, 30-second steps
code = totp.now()
print("Current code:", code, "| valid:", totp.verify(code))
print("Seconds left in this step:", 30 - int(time.time()) % 30)

# 2) Reproducible demo with a fixed secret and a fixed clock
demo = pyotp.TOTP("JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP")
t = 1_789_000_000                         # a moment in 2026 (Unix seconds)
for offset in (-30, 0, 30):
    print(f"t{offset:+d}s ->", demo.at(t + offset))
late = demo.at(t - 30)                    # code from the previous step
print("Previous-step code, strict:", demo.verify(late, for_time=t))
print("Previous-step code, valid_window=1:", demo.verify(late, for_time=t, valid_window=1))
print("Wrong code:", demo.verify("000000", for_time=t))
New secret: U63RTDMMCBEKYTP55EBT7FORVSXBW3VO (32 chars)
Current code: 669785 | valid: True
Seconds left in this step: 25
t-30s -> 922811
t+0s -> 388876
t+30s -> 553994
Previous-step code, strict: False
Previous-step code, valid_window=1: True
Wrong code: False

The strict check rejected the code from the previous 30-second step, while valid_window=1 accepted it. Phones and servers are never perfectly in sync, and users take a few seconds to type, so valid_window=1 (one step before and after, about plus or minus 30 seconds) is the usual production setting. Do not go higher than 1 or 2: each extra step gives an attacker more valid codes to guess.

Step 2: Show a QR code for the authenticator app

Authenticator apps import secrets from an otpauth:// URI. provisioning_uri() builds it with the account name and an issuer, which is the label the user sees in the app. Turn it into an image with the qrcode library, which we covered in detail in QR Code Generator in Python:

import pyotp
import qrcode

secret = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"   # in a real app: pyotp.random_base32()
uri = pyotp.TOTP(secret).provisioning_uri(name="ayesha@example.com", issuer_name="FlowForge Demo")
print(uri)

img = qrcode.make(uri)                    # scan this with Google Authenticator, Authy, 1Password...
img.save("enroll_qr.png")
print("QR saved:", img.size, "pixels")

# parse_uri reads an otpauth:// URI back into a TOTP object
again = pyotp.parse_uri(uri)
print("Parsed back:", type(again).__name__, again.name, "|", again.issuer, "| digits:", again.digits, "| interval:", again.interval)
print("Same code as original:", again.at(1_789_000_000) == pyotp.TOTP(secret).at(1_789_000_000))
otpauth://totp/FlowForge%20Demo:ayesha%40example.com?secret=JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP&issuer=FlowForge%20Demo
QR saved: (530, 530) pixels
Parsed back: TOTP ayesha@example.com | FlowForge Demo | digits: 6 | interval: 30
Same code as original: True

In a web app you would not save a file. Return the PNG as a base64 data: URL or stream it from an endpoint, show it once, and also print the secret as text for users who cannot scan. parse_uri() is handy in tests: it lets your test code play the role of the phone, as we do in the FastAPI example below.

Step 3: Block replayed codes with verify_and_get_timecode()

A plain verify() has a weakness that many tutorials ignore: a code stays valid for its whole 30-second step, and with valid_window=1 for up to about 90 seconds. Anyone who sees the code over the user's shoulder, or captures it with a phishing page, can log in with it again. RFC 6238 says a verifier should not accept the same code twice. Until pyotp 2.11 you had to compute the timecode yourself; now verify_and_get_timecode() returns the matching timecode, or False. Store the last successful timecode per user and only accept larger ones:

import pyotp

totp = pyotp.TOTP("JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP")
user = {"last_timecode": 0}               # store this column next to the secret

def check_otp(code: str, now: float) -> bool:
    timecode = totp.verify_and_get_timecode(code, for_time=now, valid_window=1)  # new in pyotp 2.11
    if timecode is False:
        return False                      # wrong or expired code
    if timecode <= user["last_timecode"]:
        return False                      # same code (or an older one) used again
    user["last_timecode"] = timecode
    return True

t = 1_789_000_000
code = totp.at(t)
print("Timecode for t:", totp.timecode(t))
print("1st login with", code, "->", check_otp(code, now=t))
print("Replay 5s later ->", check_otp(code, now=t + 5))
print("Older code from previous step ->", check_otp(totp.at(t - 30), now=t + 10))
print("Next step code ->", check_otp(totp.at(t + 30), now=t + 31))
print("Stored last_timecode:", user["last_timecode"])
Timecode for t: 59633333
1st login with 388876 -> True
Replay 5s later -> False
Older code from previous step -> False
Next step code -> True
Stored last_timecode: 59633334

The same code was refused five seconds later, an older code was refused, and the next code worked. Notice that the stored value moved to 59633334, the timecode of the code that was actually used, not the current clock step. Keep last_timecode as an integer column in your users table.

Step 4: Add 2FA to a FastAPI login

Now the full flow: the user starts setup, scans the QR code, confirms with a first code (so a mistyped secret cannot lock them out), receives eight one-time backup codes, and from then on needs password plus code. Passwords are hashed with Argon2id, and the test client at the bottom plays the user and the authenticator app:

import hashlib
import secrets
import time

import pyotp
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()
ph = PasswordHasher()
DUMMY = ph.hash("dummy")                             # equal timing for unknown users
USERS = {"ayesha": {"pw": ph.hash("S3cure!Pass"), "otp_secret": None, "pending": None,
                    "last_tc": 0, "backup": set()}}

class Login(BaseModel):
    username: str
    password: str
    otp: str | None = None

def sha(code: str) -> str:
    return hashlib.sha256(code.encode()).hexdigest()

@app.post("/2fa/setup/{username}")
def setup(username: str):
    secret = pyotp.random_base32()
    USERS[username]["pending"] = secret          # not active until confirmed
    uri = pyotp.TOTP(secret).provisioning_uri(name=username, issuer_name="FlowForge Demo")
    return {"otpauth_uri": uri}

@app.post("/2fa/confirm/{username}")
def confirm(username: str, otp: str):
    u = USERS[username]
    totp = pyotp.TOTP(u["pending"])
    tc = totp.verify_and_get_timecode(otp, valid_window=1)
    if tc is False:
        raise HTTPException(400, "Code does not match, scan the QR code again")
    u["otp_secret"], u["pending"], u["last_tc"] = u["pending"], None, tc
    codes = [secrets.token_hex(4) for _ in range(8)]   # one-time recovery codes
    u["backup"] = {sha(c) for c in codes}
    return {"enabled": True, "backup_codes": codes}

@app.post("/login")
def login(body: Login):
    u = USERS.get(body.username)
    try:
        ph.verify(u["pw"] if u else DUMMY, body.password)
    except VerifyMismatchError:
        u = None
    if u is None:
        raise HTTPException(401, "Invalid username or password")
    if u["otp_secret"]:
        if not body.otp:
            raise HTTPException(401, "OTP required")
        if sha(body.otp) in u["backup"]:
            u["backup"].discard(sha(body.otp))       # each recovery code works once
            return {"ok": True, "method": "backup code", "backup_left": len(u["backup"])}
        tc = pyotp.TOTP(u["otp_secret"]).verify_and_get_timecode(body.otp, valid_window=1)
        if tc is False or tc <= u["last_tc"]:
            raise HTTPException(401, "Invalid or reused OTP")
        u["last_tc"] = tc
        return {"ok": True, "method": "totp"}
    return {"ok": True, "method": "password only"}

client = TestClient(app)
uri = client.post("/2fa/setup/ayesha").json()["otpauth_uri"]
phone = pyotp.parse_uri(uri)                         # plays the authenticator app
print("Setup URI starts:", uri[:46] + "...")
r = client.post("/2fa/confirm/ayesha", params={"otp": "123456"})
print("Confirm with wrong code:", r.status_code, r.json()["detail"])
r = client.post("/2fa/confirm/ayesha", params={"otp": phone.now()})
backup = r.json()["backup_codes"]
print("Confirm with app code:", r.status_code, "| enabled:", r.json()["enabled"], "| backup codes:", len(backup))
print("Login, no OTP:", client.post("/login", json={"username": "ayesha", "password": "S3cure!Pass"}).json())
print("Login, same code again:", client.post("/login", json={"username": "ayesha", "password": "S3cure!Pass", "otp": phone.now()}).json())
print("Login, next code from app:", client.post("/login", json={"username": "ayesha", "password": "S3cure!Pass", "otp": phone.at(time.time() + 30)}).json())
print("Login, backup code:", client.post("/login", json={"username": "ayesha", "password": "S3cure!Pass", "otp": backup[0]}).json())
print("Backup code reused:", client.post("/login", json={"username": "ayesha", "password": "S3cure!Pass", "otp": backup[0]}).json())
print("Wrong password:", client.post("/login", json={"username": "ayesha", "password": "nope", "otp": phone.now()}).json())
Setup URI starts: otpauth://totp/FlowForge%20Demo:ayesha?secret=...
Confirm with wrong code: 400 Code does not match, scan the QR code again
Confirm with app code: 200 | enabled: True | backup codes: 8
Login, no OTP: {'detail': 'OTP required'}
Login, same code again: {'detail': 'Invalid or reused OTP'}
Login, next code from app: {'ok': True, 'method': 'totp'}
Login, backup code: {'ok': True, 'method': 'backup code', 'backup_left': 7}
Backup code reused: {'detail': 'Invalid or reused OTP'}
Wrong password: {'detail': 'Invalid username or password'}

Every rule held: a wrong code could not enable 2FA, the password alone was not enough, the code used during confirmation could not be replayed for login, the next code worked, a backup code worked exactly once, and a wrong password failed before the OTP was even checked. The demo keeps users in a dictionary to stay short; in a real app use the database models and JWT token flow from Authentication and Authorization with FastAPI in Python, and issue the access token only after the OTP step succeeds.

Production checklist

  • Encrypt the TOTP secret at rest. Unlike a password, the server must be able to read it, so you cannot hash it. Encrypt it with a key kept outside the database, for example with Fernet as shown in Encrypt and Decrypt in Python with Fernet.
  • Hash backup codes. They are random and high-entropy, so a fast SHA-256 is acceptable here; delete each one after use and let users regenerate them.
  • Rate-limit the OTP step. There are only one million six-digit codes; limit attempts per account (for example five per minute) and lock or alert on repeated failures.
  • Keep server time correct. Run NTP or chrony. If the server clock drifts by more than your window, every login fails.
  • Use the defaults. SHA-1, 6 digits and 30 seconds are what authenticator apps support everywhere; SHA-256 or 8-digit codes break some apps.
  • Re-authenticate before disabling 2FA and send the user an e-mail whenever 2FA settings change.

Quick reference

TaskCode
Installpip install pyotp "qrcode[pil]"
New secretpyotp.random_base32()
TOTP objecttotp = pyotp.TOTP(secret)
Current codetotp.now()
Code at a timetotp.at(unix_time)
Verify with drifttotp.verify(code, valid_window=1)
Verify + timecodetotp.verify_and_get_timecode(code, valid_window=1)
QR code URItotp.provisioning_uri(name=email, issuer_name="App")
Read a URIpyotp.parse_uri(uri)

Common problems and fixes

  • Codes are always rejected: check the server clock first (timedatectl on Linux), then make sure you stored the confirmed secret and not a new random one created on the next request.
  • binascii.Error: Non-base32 digit found: the secret contains spaces or characters outside A-Z and 2-7 (often a typed 0, 1 or 8). Strip spaces and store it exactly as random_base32() returned it.
  • The app shows the wrong name: set both name and issuer_name in provisioning_uri(); the issuer is what users see in their list.
  • AttributeError: 'TOTP' object has no attribute 'verify_and_get_timecode': you are on pyotp 2.10 or older; upgrade with pip install -U pyotp.
  • StarletteDeprecationWarning about httpx in tests: install httpx2; TestClient picks it up automatically.
  • Users lost their phone: that is what backup codes are for. Without them, fall back to a verified support process, never to e-mail alone.

Conclusion

Two-factor authentication in Python takes one small library: random_base32() to create a secret, provisioning_uri() plus a QR code to enrol the phone, and verify_and_get_timecode() with valid_window=1 to check codes and refuse replays. Add hashed backup codes, an encrypted secret and a rate limit, and your login is protected even when a password leaks. If your app still accepts a password alone, adding TOTP is one of the highest-value security changes you can ship in 2026.

Share:
Last updated: November 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices