Track 07 · Lesson 14 of 18Identity and login
- 01Authentication vs authorization
- 02Browser storage compared
- 03Sessions versus tokens
- 04Inside a JWT
- 05Access and refresh tokens
- 06Where to keep tokens
- 07Choosing a design
- 08The login lifecycle
- 09The token clock
- 10Dead or just unlucky? Refresh decisions
- 11Inside a secure session cookie
- 12Five tabs, one refresh
- 13“Log in with Google”: OAuth and PKCE
- 14Two-factor login
- 15Storing passwords
- 16Logging out properly
- 17Trade-offs and common mistakes
- 18Compare the designs
Two-factor login
Lesson 14 of 18· 8 min
Two-factor authentication asks for something you know (a password) plus something you have (a code from an app, email or SMS). The code must be short-lived, guess-limited, and only work for the login attempt that already passed the password step.
Bind the two steps
Then turn the binding off and play the attacker
- Start with Ana’s login, or try the attacker first.
The challenge ID#
After the correct password, the server creates an unguessable, single-use challenge ID, stores it with the user and an expiry, and requires it on every later step: verify, resend, anything. A verify call that carries only { email, code } lets anyone skip the password step and go straight to guessing codes. The same idea fits every multi-step flow: password reset, checkout, email change.
How many guesses?#
Codes are short so people can type them, which makes them guessable. Lockout after a few wrong tries, rate limits on sending new codes, and a short expiry are what keep them safe. Do the maths for your own settings:
Count the guesses
Change the length and the lockout
Code length
Wrong tries before the code dies
- Possible codes
- 1,000,000
- Guesses per code
- 5
- Chance of a hit
- 1 in 200,000
In the lifecycle#
With 2FA, the first login call returns no tokens at all, just “a code is required”. Nothing is sealed or stored until the code is verified, and from then on it’s identical to a normal login.
Log in with 2FA
Step through it
The account has two-factor authentication. The first call returns no token, so nothing is sealed until the code is verified.
Browser
Your server
Identity & API
Step 1 of 11
Same start
Exactly like a normal login.
Check yourself