Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 80 ยท Authentication and Access Control

Multi-Factor Authentication and Passkeys

Learn the authentication factors, implement the TOTP algorithm with hmac, handle recovery codes safely, and see why passkeys and WebAuthn resist phishing.

A password is something that can be guessed, stolen, phished or leaked from another site. Multi-factor authentication (MFA) adds a second, independent proof, so that the theft of one thing is no longer enough. Industry analyses repeatedly find that MFA blocks the vast majority of automated account-takeover attempts, which is why it is among the most valuable controls you can enable.

But not all second factors are equal. An SMS code can be redirected, a one-time code can be typed into a fake website, and a push approval can be spammed until a tired user taps "Accept". In this lesson you will learn the factor categories, implement the TOTP algorithm that authenticator apps use, handle recovery codes correctly, and then see why passkeys (WebAuthn) are called phishing-resistant. Good password handling comes first: see Password Storage Done Right.

The three kinds of factor

Authentication evidence falls into categories:

  • Something you know: a password, a PIN.
  • Something you have: a phone, a hardware security key, a smart card.
  • Something you are: a fingerprint or face (biometrics), usually unlocking a local device rather than being sent to a server.

MFA means combining different categories. A password plus a security question is not MFA, since both are things you know. Strength within the "have" category also varies:

Method Phishing-resistant? Notes
SMS or voice code No Vulnerable to SIM swapping, interception and phishing. Better than nothing.
Email code No Only as safe as the mailbox.
TOTP app code No Good against stolen passwords, but a fake login page can relay the code in real time.
Push approval Partly Vulnerable to "MFA fatigue" spam; number matching helps.
Hardware key / passkey (WebAuthn) Yes The credential is bound to the real website's origin.

TOTP: how authenticator apps work

Time-based one-time passwords (TOTP, RFC 6238) are built on HOTP (RFC 4226). When you scan the QR code, the server and your app share a secret (usually Base32 text). Both then compute the same short code from that secret and the current time, so no code needs to be sent between them.

The recipe:

  1. Compute the counter T = floor(unix_time / 30), the number of 30-second windows since 1970.
  2. Compute HMAC-SHA1(secret, T as 8 big-endian bytes) (or SHA-256/SHA-512 if configured).
  3. Dynamic truncation: take the last nibble (4 bits) of the digest as an offset, read 4 bytes from there, clear the top bit, and interpret them as an integer.
  4. Take that integer modulo 10^6 and left-pad with zeros to get the 6-digit code.
flowchart LR
    S["Shared secret<br/>(Base32)"] --> H["HMAC(secret, counter)"]
    T["Unix time รท 30<br/>= counter"] --> H
    H --> D["Dynamic truncation<br/>(offset from last nibble)"]
    D --> M["mod 1,000,000"]
    M --> C["6-digit code"]

The app and the server run the same function on the same secret and the same 30-second counter.

The implementation below uses only hmac, hashlib, struct and base64. It checks itself against the official test values from the RFCs (the secret 12345678901234567890, counter 0 gives 755224 and counter 1 gives 287082 for HOTP; time 59 gives 94287082 for the 8-digit TOTP test).

Python Implementing HOTP and TOTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the times 1,700,000,015, 1,700,000,029 and 1,700,000,030 share a code (same 30-second window), and a new code appears once the window changes. The secret never leaves the two devices after setup, which is why it must be stored carefully on the server (encrypted at rest, see Randomness, Key Management and Secrets). The same mechanism is a simple application of HMAC.

Verifying a code on the server

A correct verifier does more than compare strings:

  • Allow a small drift window (typically one step before and after) because clocks are never perfectly aligned.
  • Compare in constant time (hmac.compare_digest).
  • Reject replays: remember the last accepted counter and refuse the same or an older one. Otherwise a code that was shoulder-surfed or relayed can be used again within its window.
  • Limit attempts. A 6-digit code has only a million values, so without throttling an attacker could try them all. Lock or slow the account after a few failures.
Python A TOTP verifier with drift, replay and throttling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Recovery codes

Phones get lost, so every MFA system needs a recovery path, and that path is itself a target. The usual design is a set of single-use recovery codes, shown once at enrollment:

  • Generate them with a secure random generator (secrets), long enough to resist guessing (for example 10 characters from a 32-letter alphabet, about 50 bits, plus rate limiting).
  • Store only hashes, exactly as you store passwords, since a recovery code is a password-equivalent.
  • Delete a code when it is used, and tell the user by email or notification that a recovery code was used.
  • Offer a way to regenerate them (which invalidates all old codes) and make it require re-authentication.
Python Generating and redeeming recovery codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A fast hash is acceptable here only because each code is long and random (about 50 bits). For anything a human chose, use the slow functions from the previous lesson.

Why TOTP can still be phished

Imagine a fake login page at examp1e-login.test. The victim types their password and then their 6-digit code. The attacker's server instantly forwards both to the real site and receives a valid session. TOTP codes are valid for 30 seconds, which is plenty for a relay. The code proves possession of the secret, but nothing ties it to the site that asked for it.

Passkeys and WebAuthn: binding to the origin

WebAuthn (the browser API behind FIDO2 and passkeys) changes the design:

  1. At registration, the authenticator (a security key, or the platform's secure chip and password manager) creates a fresh public/private key pair for this exact website. The private key never leaves the authenticator. The server stores the public key.
  2. At login, the server sends a random challenge. The browser adds the origin it is really talking to (https://shop.example) and asks the authenticator to sign the challenge and origin. The user approves with a fingerprint, face or PIN, which unlocks the key locally. Nothing biometric is sent.
  3. The server verifies the signature with the stored public key, checks the challenge is the one it issued, and checks that the origin is its own.
sequenceDiagram
    participant U as User
    participant A as Authenticator
    participant B as Browser
    participant S as Server (shop.example)
    S->>B: random challenge
    B->>A: sign(challenge + origin as seen by browser)
    A->>U: ask for fingerprint, face or PIN
    U-->>A: approve
    A-->>B: signature using the key made for shop.example
    B->>S: signature and origin
    S->>S: verify with stored public key, challenge and origin

The browser, not the user, supplies the origin. A look-alike site gets a different origin and no matching key.

On the fake site the browser reports https://examp1e-login.test as the origin. The authenticator has no credential for that domain, so there is nothing to sign, and even a forwarded signature would carry the wrong origin and be rejected by the real server. Because the server only holds public keys, a database breach reveals nothing that can be replayed. Synced passkeys (stored in a cloud password manager) trade a little of the hardware key's isolation for much better recovery and adoption.

The real WebAuthn API runs in the browser against hardware, so it cannot execute in this lesson's sandbox. Here is what the browser code looks like (read-only):

JavaScript
// Registration (simplified): the server supplies options with a random challenge
const credential = await navigator.credentials.create({
  publicKey: {
    challenge: serverChallengeBytes,
    rp: { name: "Shop Example", id: "shop.example" },
    user: { id: userIdBytes, name: "[email protected]", displayName: "Alice" },
    pubKeyCredParams: [{ type: "public-key", alg: -7 }],   // ES256
    authenticatorSelection: { residentKey: "preferred", userVerification: "required" },
  },
});
// Send credential.response to the server, which stores the public key.

// Login
const assertion = await navigator.credentials.get({
  publicKey: { challenge: serverChallengeBytes, rpId: "shop.example", userVerification: "required" },
});

The next demo is an honest stand-in. Real passkeys use asymmetric signatures (ECDSA or Ed25519), which Python's standard library does not provide, so the stand-in uses an HMAC keyed per origin to model the binding idea only. It is not how WebAuthn is implemented.

Python Origin binding: stand-in for a passkey login

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rolling out MFA sensibly

  • Require MFA for administrators and anything that can move money or change security settings first, then extend it to everyone.
  • Offer passkeys as the preferred option and TOTP as a fallback; discourage SMS but do not forbid it if it is the only choice for some users.
  • Register at least two factors per user (for example a passkey and recovery codes) so one lost device is not a lockout.
  • Treat the recovery and "I lost my phone" flows as part of your attack surface: they must be at least as strong as the login they replace.
  • Add number matching or additional context to push prompts, and rate-limit prompts to fight fatigue attacks.
  • Log MFA enrollment, removal and recovery events and alert the user (Logging, Log Analysis and SIEM).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pair counts as true multi-factor authentication?

    MFA combines different categories: something you know plus something you have. A password, security question, PIN and second password are all knowledge factors.
  2. 2. In TOTP, what do the server and the authenticator app share after setup?

    Only the secret is shared once. The code is derived from HMAC(secret, floor(time/30)), so nothing needs to be transmitted at login time except the code the user types.
  3. 3. Why should a TOTP verifier remember the last accepted counter?

    Without replay protection, a code that was observed or relayed can be reused for as long as it is valid.
  4. 4. Why are passkeys (WebAuthn) resistant to phishing?

    The browser supplies the true origin and the authenticator only holds keys for that site. The user cannot be tricked into handing over a reusable code.
  5. 5. How should the server store recovery codes?

    A recovery code is equivalent to a password. Store only hashes, make codes single-use, and notify the user when one is redeemed.

Summary

  • MFA combines factors from different categories: know, have, are.
  • TOTP is HMAC(secret, floor(time/30)) with dynamic truncation; verify with a small drift window, constant-time comparison, replay protection and throttling.
  • Store recovery codes hashed and single-use, and secure the recovery path as carefully as login.
  • SMS, email and TOTP codes can be phished by real-time relay; push prompts can be spammed.
  • Passkeys use a per-site key pair and sign a server challenge together with the origin, which makes them phishing-resistant and leaves nothing replayable on the server.

Next: Sessions, Cookies and JWTs, which covers what happens after a successful login.