Appearance
MFA, Passkeys and Account Recovery
28. What is Multi-Factor Authentication (MFA)?
The short answer
MFA means proving your identity with two or more different kinds of evidence: something you know, like a password; something you have, like a phone or security key; and something you are, like a fingerprint. Stealing one factor is then not enough. A phished password alone cannot log in. Two passwords are not MFA, because they are the same kind. Factors differ a lot in strength: passkeys and security keys resist phishing, app codes are good, and SMS codes are the weakest because of SIM-swap attacks and interception.
| Factor | Kind | Phishing-resistant? | Notes |
|---|---|---|---|
| Passkey, security key | Have, plus are or know to unlock | Yes | Strongest; bound to the real site |
| Push approval with number matching | Have | Partly | Number matching stops blind "approve" taps |
| Authenticator app code (TOTP) | Have | No | Can be typed into a fake site |
| SMS or voice code | Have | No | SIM swap, interception; NIST now calls it restricted |
| Email link or code | Have, the inbox | No | Only as strong as the email account |
Why "phishing-resistant" is the line that matters. A fake login page can ask for your password and your six-digit code, then use both on the real site within seconds. This is a real-time phishing relay, and tools for it are sold openly. A passkey cannot be relayed: the browser only uses it for the real domain it was created on (question 31).
MFA fatigue. Attackers with a stolen password send push request after push request at 2 a.m. until the user taps "approve" to make it stop. Defences: number matching, where the user must type the number shown on the login screen; limits on push requests; and showing the location and app in the prompt.
29. What is adaptive or risk-based authentication?
The short answer
Adaptive authentication changes how much proof it asks for based on how risky each login looks. It scores signals such as a new device, an unusual country, impossible travel, a known-bad IP address, a breached password or odd behaviour. A low-risk login from the usual laptop may need nothing extra. A risky one gets an MFA challenge, and a very risky one is blocked. This keeps everyday logins smooth while making attacks harder. It is also applied to sensitive actions, such as asking for MFA again before changing the payout bank account.
Signals, and what they suggest:
| Signal | Suggests |
|---|---|
| Known device, usual city, office hours | Low risk |
| New device or new browser | Medium: ask for MFA |
| London at 10:00, then Sydney at 10:30 | Impossible travel: block or strong MFA |
| IP on a list of anonymising proxies or botnets | High risk |
| Password found in a breach list | Force a password change |
| Many failed logins across many accounts from one network | Password spraying in progress |
A simple rule set, as code:
ts
type Risk = 'low' | 'medium' | 'high'
function scoreLogin(s: LoginSignals): Risk {
if (s.ipReputation === 'bad' || s.impossibleTravel) return 'high' // (1)
if (!s.knownDevice || s.newCountry) return 'medium' // (2)
return 'low'
}
const action = { low: 'allow', medium: 'require_mfa', high: 'block_and_alert' } as const- Strong signals of attack block the login and alert security.
- Unfamiliar but plausible situations step up to MFA.
Real identity providers use many more signals and machine learning. In Microsoft Entra ID this is part of Conditional Access (the Conditional Access question).
30. What is passwordless authentication?
The short answer
Passwordless authentication logs users in without any password to remember or type. The main methods are passkeys, where the device proves possession of a private key and the user unlocks it with a fingerprint, face or PIN; magic links sent by email; and one-time codes sent by email or SMS. Passkeys are both easier and much safer than passwords, because there is nothing to phish, reuse or leak from a database. Magic links and codes are convenient but only as secure as the inbox or phone number.
| Method | How | Phishing-resistant? | Server stores |
|---|---|---|---|
| Passkey | Device signs a challenge | Yes | Public key only |
| Magic link | Click a one-time link in email | No | Hash of a short-lived token |
| Email or SMS code | Type a short code | No | Hash of the code, with expiry |
| Device login, e.g. Windows Hello for Business | Device key tied to the OS login | Yes | Public key |
What happens to the password. In a full passwordless setup there is none. In practice many sites keep a password as a fallback, which leaves the old weakness in place. The safest path is to let users add a passkey, then let them remove their password once they have two passkeys or a passkey and recovery codes.
31. What are passkeys, and how do they work?
The short answer
A passkey is a key pair created by your device for one website. The private key stays on your device, or in your password manager's encrypted sync, and never goes to the website. The site stores only the public key. To log in, the site sends a random challenge, your device asks for your fingerprint, face or PIN, then signs the challenge with the private key. The site checks the signature with the public key. Because the browser binds each passkey to the real domain, a fake site cannot ask for it, and a stolen database contains nothing usable.
Registration, the other half:
- The user, already logged in, clicks "Create a passkey".
- The site sends a challenge and its own domain, the relying party ID.
- The device creates a new key pair for that domain, after a fingerprint or PIN.
- The device returns the public key and a credential ID. The site saves them against the user.
Synced and device-bound passkeys:
| Synced passkey | Device-bound passkey | |
|---|---|---|
| Lives in | Apple, Google or a password manager's encrypted sync | One security key or device |
| Survives losing a phone | Yes | No: register a second key |
| Typical use | Consumers | High-security staff and admins |
Why a stolen database is harmless. The server stores only public keys. A public key can check signatures but cannot make them. There is nothing to crack and nothing to reuse on other sites.
32. What are WebAuthn and FIDO2?
The short answer
FIDO2 is the overall standard from the FIDO Alliance for phishing-resistant, public-key login. It has two parts. WebAuthn is the W3C browser API that websites call, navigator.credentials.create() to register and navigator.credentials.get() to sign in. CTAP2 is the protocol the browser or operating system uses to talk to an authenticator, such as a USB security key, a phone over Bluetooth, or the built-in fingerprint reader. A passkey is the user-friendly name for a FIDO2 credential.
Sign-in in the browser:
ts
const options = await fetch('/webauthn/login/options').then((r) => r.json()) // (1)
const credential = await navigator.credentials.get({
publicKey: {
challenge: base64urlToBuffer(options.challenge), // (2)
rpId: 'shop.example', // (3)
userVerification: 'required', // (4)
},
})
await fetch('/webauthn/login/verify', { method: 'POST', body: JSON.stringify(serialize(credential)) }) // (5)- The server creates a random challenge and remembers it in the session.
- The challenge the device must sign, so an old signature cannot be replayed.
- The relying party ID, the domain the passkey belongs to. The browser refuses if the page is not on this domain.
- Require fingerprint, face or PIN, not just possession of the device.
- The server checks the signature, the challenge, the origin, and a signature counter or backup flags.
Use a library for the server side. Checking WebAuthn responses means parsing binary data structures and many details. In Node, a maintained library such as SimpleWebAuthn does this. Do not write it yourself.
33. What is the difference between TOTP and HOTP?
The short answer
Both make a short one-time code from a shared secret and a moving number, using HMAC. HOTP, HMAC-based one-time password, uses a counter that goes up by one each time a code is used. TOTP, time-based one-time password, uses the current time divided into 30-second steps, so the code changes every 30 seconds on its own. TOTP is what Google Authenticator and Microsoft Authenticator use. HOTP is found on some hardware tokens with a button. TOTP is easier because the two sides never need to resync a counter.
| HOTP | TOTP | |
|---|---|---|
| Standard | RFC 4226 | RFC 6238 |
| Moving number | A counter | Unix time ÷ 30 seconds |
| Code changes | When used | Every 30 seconds |
| Unused codes | Stay valid until used, a risk | Expire in about 30 seconds |
| Out-of-sync problem | Counter drift, needs a look-ahead window | Clock drift, allow one step either side |
Both are the same function with a different input. TOTP is literally HOTP with the counter replaced by floor(unixTime / 30) (question 34 shows the code).
34. How do authenticator applications generate one-time codes?
The short answer
At setup, the server makes a random secret and shows it as a QR code. The app scans and stores it. From then on, both the app and the server independently compute the same code: take the current Unix time, divide by 30 to get a step number, compute an HMAC-SHA1 of that number with the secret, pick four bytes from the result at a position given by its last byte, and turn them into a six-digit number. No network is needed. The server accepts the code if it matches the current step, or one step before or after to allow for clock drift.
ts
import { createHmac } from 'node:crypto'
function hotp(secret: Buffer, counter: number, digits = 6): string {
const msg = Buffer.alloc(8)
msg.writeBigUInt64BE(BigInt(counter)) // (1)
const mac = createHmac('sha1', secret).update(msg).digest() // (2)
const offset = mac[mac.length - 1] & 0x0f // (3)
const code = (mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits // (4)
return code.toString().padStart(digits, '0') // (5)
}
const totp = (secret: Buffer, now = Date.now()) => hotp(secret, Math.floor(now / 1000 / 30)) // (6)
const secret = Buffer.from('12345678901234567890')
console.log(hotp(secret, 0), hotp(secret, 1)) // 755224 287082- The moving number as 8 bytes, big-endian, exactly as the standard requires.
- HMAC-SHA1 of that number, keyed with the shared secret: 20 bytes of output.
- Dynamic truncation. The last 4 bits of the HMAC pick a starting position from 0 to 15.
- Take 4 bytes from there, clear the top bit so the number is positive, and keep the last 6 decimal digits.
- Pad with zeros, so
42becomes000042. - TOTP is HOTP with the counter set to the number of 30-second steps since 1970.
The two printed values are the official test values from RFC 4226 for that secret, so you can check an implementation against them.
What the QR code contains: a URL such as otpauth://totp/Shop:asha@shop.example?secret=JBSWY3DPEHPK3PXP&issuer=Shop. The secret is in Base32. Anyone who sees that QR code can make your codes forever, so show it only once, over HTTPS, and store the secret encrypted on the server.
Server-side rules: accept each code only once, to stop replay within its 30 seconds; rate limit attempts, since six digits is only a million options; and allow one step of drift either side.
35. What are recovery codes, and how should they be protected?
The short answer
Recovery codes are a set of one-time backup codes, typically 8 to 10, given to the user when they turn on MFA, to log in if they lose their phone or security key. Each code works once. The server must store them hashed, like passwords, never in plain text. Show them only once, ask the user to save them somewhere safe such as a password manager, mark each one used, rate limit attempts, notify the user when one is used, and let them generate a fresh set, which cancels the old one.
ts
import { randomBytes } from 'node:crypto'
import argon2 from 'argon2'
async function createRecoveryCodes(userId: string) {
const codes = Array.from({ length: 10 }, () => randomBytes(5).toString('hex')) // (1)
const hashes = await Promise.all(codes.map((c) => argon2.hash(c))) // (2)
await recoveryCodes.replaceAll(userId, hashes) // (3)
return codes // (4)
}- Ten codes of 10 hex characters, 40 random bits each. Rate limiting makes guessing hopeless.
- Hash each one with a slow hash, exactly like a password.
- Replace any old set, so a leaked old list stops working.
- Return the plain codes once, for the page that shows them. They are never stored or shown again.
Recovery is the weak point attackers aim for. An attacker who cannot beat your MFA will try the "I lost my phone" path. Support staff who disable MFA after a convincing phone call undo all your security. Make recovery require something strong: a recovery code, a second registered passkey, or an identity check with a waiting period and a notice to the old email address.
36. What is device trust in authentication?
The short answer
Device trust means the login decision also depends on which device is being used and whether it is healthy, not just on the user's credentials. A device can be trusted because it is company-managed and enrolled in device management, has disk encryption, a screen lock and up-to-date software, and carries a certificate or hardware-bound key proving it is that device. Policies then say, for example, "finance apps only from managed, compliant laptops". Consumer sites use a lighter version: "remember this device for 30 days" to skip MFA.
| Level | What it proves | Example |
|---|---|---|
| Remembered browser | Same browser as before | A long-lived signed cookie after MFA |
| Registered device | A specific device key | A passkey or device certificate |
| Managed and compliant | The company controls it and it meets policy | Enrolled in Intune, encrypted, patched |
"Remember this device" done safely: after a successful MFA login, set a separate long-lived, HttpOnly, Secure cookie holding a random token. Store its hash on the server, linked to the user, with an expiry. List remembered devices in account settings, and let the user revoke them. Revoke all of them when the password changes.
37. How should account lockout be designed to resist abuse without enabling denial of service?
The short answer
A hard lock after a few failures lets anyone lock any user out on purpose, just by typing wrong passwords for their email. So avoid permanent locks. Instead, slow down failures with growing delays, lock only temporarily, for 15 minutes for example, and count failures per account and per source. After a few failures, add a challenge, such as a CAPTCHA, rather than a block. Keep known devices working even while an account is under attack. Always let the real user recover by a strong route, such as a password reset or a passkey.
A layered design:
| Failures on the account | Response |
|---|---|
| 1 to 3 | Normal error |
| 4 to 5 | Add a short delay, show a CAPTCHA |
| 6 to 10 | Temporary lock of 15 minutes for unknown devices; email the user |
| Many, from many IPs | Alert the security team; require MFA or a reset |
Why known devices keep working. If the attacker is hammering asha@shop.example from a botnet, the lock applies to new devices. Asha's own laptop, with its remembered-device cookie (question 36), still logs in. The attack is slowed, and she is not punished for it.
Other rules:
- Use the same error message and timing whether the email exists or not, to avoid user enumeration (the brute force question).
- Store counters in Redis with an expiry, so they reset on their own and work across instances.
- Never tell the attacker how many attempts are left.
38. How would you design a secure password reset flow?
The short answer
The user enters their email. You always reply "if an account exists, we sent a link", so attackers cannot discover accounts. If the account exists, create a long random single-use token, store only its hash with a short expiry of about 15 to 30 minutes, and email a link containing the token. When the link is used, check the hash and expiry, let the user set a new password, then delete the token, revoke all existing sessions, and send a "your password was changed" notice. Build the link from a configured site URL, never from the request's Host header.
ts
import { randomBytes, createHash } from 'node:crypto'
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex')
app.post('/password-reset', resetLimiter, async (req, res) => {
const user = await users.findByEmail(req.body.email)
if (user) {
const token = randomBytes(32).toString('base64url') // (1)
await resetTokens.insert({ userId: user.id, hash: sha256(token), expiresAt: Date.now() + 30 * 60_000 }) // (2)
await mail.send(user.email, `${config.PUBLIC_URL}/reset?token=${token}`) // (3)
}
res.status(202).json({ message: 'If an account exists, we sent a link.' }) // (4)
})
app.post('/password-reset/confirm', async (req, res) => {
const row = await resetTokens.takeByHash(sha256(req.body.token)) // (5)
if (!row || row.expiresAt < Date.now()) throw new HttpError(400, 'Link expired or already used')
await users.setPasswordHash(row.userId, await argon2.hash(req.body.newPassword))
await sessions.revokeAllForUser(row.userId) // (6)
await mail.sendPasswordChangedNotice(row.userId)
res.status(204).end()
})- 256 random bits, safe to put in a URL.
- Store only the hash. Someone who reads the database cannot use the links. SHA-256 is fine here because the token is random and long, unlike a human password.
- The link uses a configured URL, so a faked
Hostheader cannot redirect the token to an attacker's site. - The same reply whether or not the account exists. Send email in a background job so the timing does not differ either.
- Find and delete the token in one step, so it can be used only once even if two requests race.
- End every existing session. If an attacker was logged in, they are now out.
Also: keep the token out of logs and analytics, set Referrer-Policy: no-referrer on the reset page so the token does not leak to third parties, and do not log the user in automatically if they have MFA. Make them complete MFA first.
39. How would you design an email verification flow?
The short answer
At signup, mark the email as unverified, create a random single-use token, store its hash with an expiry of about 24 hours, and email a link containing it. When the user clicks, check the hash and expiry, mark the email verified, and delete the token. Until verified, limit what the account can do, for example no purchases or invitations. When a user changes their email, verify the new address before switching, and notify the old one. Rate limit "resend" requests.
Why verify at all:
- To confirm the user really owns the address, before you send receipts and password resets there.
- To stop someone signing up with another person's email, then later claiming that person's account or linking it through SSO.
- To keep the mailing list clean, so your emails do not get marked as spam.
The account takeover trap with SSO. An attacker signs up on your site with asha@company.example and never verifies it. Later the real Asha logs in with "Sign in with Google" using the same email. If your code links the Google login to the existing account by email, the attacker's account now belongs to Asha, and the attacker knows its password. Only link accounts by email when both sides have verified the address, and prefer linking by the IdP's stable sub ID (the ID token question).
| Step | Rule |
|---|---|
| Token | Random, 32 bytes, stored hashed, single use |
| Expiry | About 24 hours |
| Before verified | Restricted features |
| Email change | Verify the new address; notify the old one; keep the old one active until then |
| Resend | Rate limited; a new token cancels the old one |