
Passkeys and 2FA for Web Apps: A Practical Implementation Guide (2026)
Passwords are the weakest part of most web apps. Users reuse them, attackers phish them, and a leaked database turns them into a shopping list. Two-factor authentication helps, but the common forms of it, such as text messages and push prompts, can still be phished or tricked.
Passkeys fix the root problem. They replace the shared secret with public-key cryptography that is bound to your website’s domain, so a fake site cannot collect anything useful. In 2026 they are no longer experimental. WebAuthn Level 3 became a W3C Recommendation on August 25, 2026, and the FIDO Alliance reports that more than a third of successful sign-ins on participating services now use a passkey.
This guide shows how to build it. You will get the concepts in plain terms, the decisions to make before you write code, and working server and browser code for passkeys. You will also get a time-based one-time password flow for apps that need it, recovery codes, and a list of the attacks that still work against weak fallbacks.
I tested what I could. The passkey code compiles against SimpleWebAuthn 14.1.0 with strict TypeScript, and I ran its option generators to show real output. The one-time password code passes the official test vectors from RFC 4226 and RFC 6238, and the recovery code logic runs as described. I did not test a live ceremony with a real authenticator or browser, so test those yourself before shipping. The standards and statistics come from NIST, the W3C, the FIDO Alliance, and OWASP, which I checked on November 18 and 19, 2026.
This is the fourth article in my security series. It pairs with my guides to secrets management, dependency scanning, and supply chain security, and it connects to my explainer on post-quantum cryptography.
Table of Contents
- The Short Answer
- Why Passwords and Weak 2FA Fail
- Passkeys in Plain English
- What NIST Says
- Design Decisions Before You Code
- The Data Model
- Implementing Passkeys
- What the Server Must Verify
- Keeping Passkeys in Sync
- TOTP: Authenticator App Codes
- Recovery Codes and Account Recovery
- Sessions and Step-Up Authentication
- Attacks and Defenses
- Testing and Rollout
- Libraries and Providers
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
Build passkeys as your strongest option, keep a standards-based authenticator app as a fallback, and make sure the fallback is not the weakest door into your accounts.
| If you are building… | Do this |
|---|---|
| A new app | Offer passkeys as the primary sign-in, with email-based account creation and a TOTP or recovery option as the backup. |
| An existing app with passwords | Add passkey creation after a successful password sign-in, then make passkey sign-in the prominent path. |
| An app with sensitive data or admin users | Require a phishing-resistant factor, and require user verification for step-up actions. |
| A small app on a hosted auth service | Use the provider’s passkey support if it has one. Check its maturity first, as section 15 explains. |
| An app that uses SMS codes today | Keep SMS only as a last resort, and plan to remove it. NIST treats phone-network codes as a restricted authenticator. |
Three rules cover most of the value.
- Use WebAuthn for the strong path: It is the only widely available phishing-resistant method, according to CISA.
- Protect recovery as hard as sign-in: Attackers go around strong factors through weak fallbacks.
- Never ship auth code you have not tested: Use a maintained library, and test the unhappy paths.
2. Why Passwords and Weak 2FA Fail
Official docs: CISA: implementing phishing-resistant MFA, OWASP Multifactor Authentication Cheat Sheet
A shared secret has a basic flaw: anyone who learns it can use it. Phishing sites, malware, database leaks, and credential stuffing all exploit that flaw.
CISA’s October 2022 fact sheet ranks forms of multi-factor authentication from strongest to weakest. I reproduce the structure below.
| Rank | Method | Weakness according to CISA |
|---|---|---|
| 1 | FIDO/WebAuthn and PKI-based authentication | Resistant to phishing. Push bombing, SS7, and SIM swap attacks do not apply. |
| 2 | App-based codes and push with number matching | Vulnerable to phishing. Number matching reduces push bombing. |
| 3 | Push without number matching | Vulnerable to push bombing and user error. |
| 4 | SMS or voice codes | Vulnerable to phishing, SS7 attacks, and SIM swap. CISA calls it a last resort. |
CISA also states that the only widely available phishing-resistant authentication is FIDO/WebAuthn. That is why this guide centers on it.
The OWASP cheat sheet gives the same direction in practical terms. It prefers phishing-resistant authenticators that bind authentication to the legitimate origin. It treats standards-based TOTP apps as the sensible default for users who do not use WebAuthn. It says SMS and voice should not protect applications that hold personally identifiable information, and it warns that requiring two instances of the same factor is not multi-factor authentication.
The key insight: origin binding
A phishing site works by convincing a person to hand over something. With a passkey there is nothing to hand over. The browser tells the authenticator which domain is asking, and the authenticator only signs for a credential created on that exact domain. A look-alike domain gets no signature.
3. Passkeys in Plain English
Official docs: WebAuthn Level 3 (W3C Recommendation), FIDO Passkey Index 2026
A passkey is a public-key credential. When a user creates one, their device generates a key pair. The private key stays on the device or in the user’s password manager, and your server stores the public key. To sign in, your server sends a random challenge, the device signs it, and your server checks the signature with the stored public key.
Your server never holds anything an attacker could replay, because the challenge is different every time. A database leak exposes public keys, which are useless on their own.
The vocabulary
| Term | Meaning |
|---|---|
| WebAuthn | The browser API, standardized by the W3C, for creating and using public-key credentials. |
| FIDO2 | The umbrella of FIDO Alliance specifications that includes WebAuthn. |
| Passkey | A friendly name for a discoverable WebAuthn credential, often synced between a user’s devices. |
| Relying party (RP) | Your website or app. You are the party that relies on the authenticator. |
| RP ID | The domain that the credential is bound to, such as example.com. |
| Authenticator | The thing that holds the private key: a phone, a laptop, a password manager, or a hardware security key. |
| Credential ID | A unique identifier for one credential, which you store. |
| User handle | An opaque identifier for the account, stored with a discoverable credential. |
| User presence (UP) | A flag saying the person touched or acknowledged the authenticator. |
| User verification (UV) | A flag saying the authenticator verified the person with a PIN, fingerprint, or face scan. |
| Backup eligible (BE) | A flag, fixed at creation, saying the credential can be synced or backed up. |
| Backup state (BS) | A flag saying whether the credential currently is synced or backed up. |
| Attestation | Optional proof of what kind of authenticator created the credential. |
Synced and device-bound passkeys
A multi-device, or synced, passkey lives in a password manager or platform account and moves between the user’s devices. It is convenient and survives a lost phone. A single-device passkey stays on one authenticator, such as a hardware security key. The backup-eligible flag tells you which kind you are dealing with, and the flag is permanent for a given credential.
Discoverable credentials
A discoverable credential, also called a resident key, lets the authenticator offer an account without the user typing a username first. That is what makes the “one tap sign-in” experience and the browser’s autofill prompt possible. For passkeys as the primary login, you want discoverable credentials.
What changed in WebAuthn Level 3
The W3C published WebAuthn Level 3 as a Recommendation on August 25, 2026, and it replaces Level 2 from 2021. The Level 3 features I saw in the specification include related origin requests, user-agent hints, a signal API for keeping credentials in sync, a large blob extension, getClientCapabilities(), and JSON serialization helpers such as parseCreationOptionsFromJSON() and parseRequestOptionsFromJSON().
Adoption
- Passkeys in circulation: the FIDO Alliance’s 2026 report, as summarized in coverage, estimated about 5 billion passkeys in active use. I could not confirm the number from the report PDF itself.
- Sign-ins: the FIDO Passkey Index 2026, dated October 15, 2026, says 36 percent of successful sign-ins now use a passkey, up from 26 percent in 2025.
- Success rate: passkey sign-ins succeeded 93 percent of the time, compared with 78 percent for traditional multi-factor sign-ins.
- Speed: the index says passkey sign-ins are nearly three times faster, saving an average of 27 seconds.
These are the Alliance’s own figures from participating companies. The page I read did not name the participants or the sample sizes, so treat the numbers as directional.
4. What NIST Says
Official docs: NIST SP 800-63B-4
NIST’s digital identity guidelines are the most detailed public rulebook for authentication, and many standards copy them. The current edition, SP 800-63B-4, is dated August 26, 2025 and supersedes the earlier version. These are the parts that matter for a web app.
| Topic | What the guidelines say |
|---|---|
| Phishing resistance | At AAL2, verifiers must offer at least one phishing-resistant option. Manually entered OTPs and out-of-band codes are not phishing-resistant. |
| Syncable authenticators | Allowed at AAL2 under conditions in the normative Appendix B. They must not be used at AAL3, because syncing violates the non-exportability requirement. |
| SMS and phone network codes | Restricted. You must offer alternatives and consider risk signals such as a recent SIM change. |
| Email codes | Email must not be used for out-of-band authentication. |
| Approval-only push prompts | No longer considered acceptable, because the user approves without transferring a secret. |
| OTP rules | Secrets must meet the 112-bit minimum. Clock-based values must change at least every two minutes. Each OTP is accepted only once. |
| Throttling | Unless stated otherwise, limit consecutive failed attempts to no more than 100 by disabling that authenticator. Organizations may set a lower limit. |
| Recovery codes | Look-up secrets must be used once and delivered securely, and online delivery needs an AAL2 or higher session. |
What Appendix B means for your code
Appendix B on syncable authenticators is the part of NIST that connects directly to WebAuthn flags.
- User verified (UV): verifiers must request UV as preferred and must inspect the response. If the user was not verified, treat the authenticator as single-factor. That decides whether a passkey counts as multi-factor.
- User present (UP): verifiers should confirm that it is set.
- Backup eligible (BE): it distinguishes device-bound credentials from cloneable ones. Verifiers may use it to restrict syncable passkeys.
- Backup state (BS): it says whether a credential is currently synced. Agencies should not condition acceptance on it for public-facing applications, because of user experience concerns.
- Sync fabric protection: keys in the sync service must be encrypted, and access to them must be protected by multi-factor authentication equivalent to AAL2.
You are probably not a federal agency. These rules still give you a defensible baseline for deciding what to require.
5. Design Decisions Before You Code
Official docs: OWASP Multifactor Authentication Cheat Sheet
Most passkey projects go wrong in design, not in code. Settle these questions first.
Decision 1: what role does the passkey play?
| Model | How it works | Good for |
|---|---|---|
| Passkey as the primary login | No password needed. The passkey proves possession and, with user verification, identity. | New apps, consumer apps, anything that wants less friction |
| Passkey as a second factor | The user enters a password, then taps a security key or passkey. | Apps that cannot drop passwords yet |
| Passkey alongside a password | Both exist. The user picks, and you nudge toward the passkey. | Migration from an existing password system |
A passkey as the primary login with user verification is a multi-factor authentication by itself. NIST’s rule is that if the user was not verified, you must treat the authenticator as single-factor.
Decision 2: choose your RP ID carefully
The RP ID is the domain that credentials are bound to, and it cannot change later without breaking every passkey. Use the registrable domain, such as example.com, so passkeys work on www.example.com and login.example.com.
If you run several domains, Related Origin Requests let one RP ID serve other origins. You publish a JSON file at https://{RP ID}/.well-known/webauthn with an origins array. Chrome supports a maximum of 5 labels, and the article I read said Chrome and Safari support the feature while Firefox was still considering it as of January 2026.
Decision 3: user verification policy
preferred: this is the default. Most authenticators verify the user, and you inspect the flag.required: use it for step-up actions such as changing the email address or approving a payment.discouraged: SimpleWebAuthn’s documentation suggests it when a passkey is used as a second factor after a password, because the password already counts as a factor. Remember that an unverified authenticator is single-factor.
Decision 4: attestation
Leave attestation at none unless you have a specific need, such as verifying that credentials come from approved hardware keys. Consumer apps rarely need it, and requesting it can add friction.
Decision 5: algorithms
Offer the common set: ES256, RS256, and EdDSA. SimpleWebAuthn’s default list adds a surprise on newer runtimes, which I describe in section 7.
Decision 6: what happens when a user loses everything
Write the recovery policy now, before any code. Section 11 covers the choices. The most important rule is that recovery must not be weaker than your strongest sign-in method.
Decision 7: multiple passkeys per account
Let each user register several passkeys, give them names, and show when each was last used. A phone and a laptop plus a recovery path is the normal healthy state. Clerk’s documentation, as summarized in a comparison I read, caps accounts at 10 passkeys, which shows that providers set limits.
6. The Data Model
Official docs: WebAuthn Level 3: user handle and challenges
You need to store a few things per credential and per ceremony. This SQL is an example for PostgreSQL, and I did not run it, so adapt it to your database.
CREATE TABLE passkeys (
id text PRIMARY KEY, -- credential ID, base64url
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
public_key bytea NOT NULL,
counter bigint NOT NULL DEFAULT 0,
transports text[],
device_type text NOT NULL, -- 'singleDevice' or 'multiDevice'
backed_up boolean NOT NULL,
name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
last_used_at timestamptz
);
CREATE TABLE webauthn_challenges (
key text PRIMARY KEY,
challenge text NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE TABLE totp_factors (
user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
secret_enc bytea NOT NULL, -- encrypted, never plaintext
last_used_step bigint,
confirmed_at timestamptz
);
CREATE TABLE recovery_codes (
id bigserial PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash text NOT NULL,
used_at timestamptz
);
Rules for the data
- User handle: the specification says it is an opaque byte sequence of at most 64 bytes, and it must not contain personally identifying information. Use a random identifier, not an email address or a username.
- Challenges: they must be randomly generated on the server, and the specification says they should be at least 16 bytes. Store each one temporarily, accept it once, and delete it. SimpleWebAuthn generated 43-character base64url challenges in my run, which is 32 bytes.
- Counters: store the signature counter, but see section 8 for how to use it.
- Flags: store the device type and backed-up state, so you can build policies and show users what they have.
- TOTP seeds: encrypt them, ideally with a key held in a key management service. My secrets management guide explains how to handle the encryption key.
7. Implementing Passkeys
Official docs: SimpleWebAuthn, web.dev: passkey form autofill
I use SimpleWebAuthn here because it is maintained, MIT licensed, and written in TypeScript. Version 14.1.0 of the server package was published on November 6, 2026 and needs Node 22 or later. The browser package was at 14.0.0. Every call below compiled with strict TypeScript against those versions.
Server side
import {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
} from "@simplewebauthn/server";
import type {
RegistrationResponseJSON,
AuthenticationResponseJSON,
WebAuthnCredential,
} from "@simplewebauthn/server";
const rpName = "Example App";
const rpID = "example.com";
const origin = "https://example.com";
interface StoredPasskey {
id: string;
userId: string;
publicKey: WebAuthnCredential["publicKey"];
counter: number;
transports?: string[];
deviceType: "singleDevice" | "multiDevice";
backedUp: boolean;
name: string;
}
// Replace with a real database. Challenges must be single-use and expire quickly.
declare const db: {
getUserPasskeys(userId: string): Promise<StoredPasskey[]>;
getPasskeyById(id: string): Promise<StoredPasskey | null>;
savePasskey(p: StoredPasskey): Promise<void>;
updateCounter(id: string, counter: number): Promise<void>;
saveChallenge(key: string, challenge: string): Promise<void>;
takeChallenge(key: string): Promise<string | null>;
};
export async function beginRegistration(user: { id: string; email: string }) {
const existing = await db.getUserPasskeys(user.id);
const options = await generateRegistrationOptions({
rpName,
rpID,
userName: user.email,
userID: new TextEncoder().encode(user.id),
attestationType: "none",
excludeCredentials: existing.map((p) => ({
id: p.id,
transports: p.transports,
})),
authenticatorSelection: {
residentKey: "required",
userVerification: "preferred",
},
});
await db.saveChallenge(`reg:${user.id}`, options.challenge);
return options;
}
export async function finishRegistration(
userId: string,
body: RegistrationResponseJSON,
) {
const expectedChallenge = await db.takeChallenge(`reg:${userId}`);
if (!expectedChallenge) throw new Error("No pending registration");
const verification = await verifyRegistrationResponse({
response: body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
requireUserVerification: false,
});
if (!verification.verified) throw new Error("Registration not verified");
const { credential, credentialDeviceType, credentialBackedUp } =
verification.registrationInfo;
await db.savePasskey({
id: credential.id,
userId,
publicKey: credential.publicKey,
counter: credential.counter,
transports: credential.transports,
deviceType: credentialDeviceType,
backedUp: credentialBackedUp,
name: "New passkey",
});
}
export async function beginAuthentication(sessionKey: string) {
const options = await generateAuthenticationOptions({
rpID,
userVerification: "preferred",
});
await db.saveChallenge(`auth:${sessionKey}`, options.challenge);
return options;
}
export async function finishAuthentication(
sessionKey: string,
body: AuthenticationResponseJSON,
) {
const expectedChallenge = await db.takeChallenge(`auth:${sessionKey}`);
if (!expectedChallenge) throw new Error("No pending authentication");
const stored = await db.getPasskeyById(body.id);
if (!stored) throw new Error("Unknown passkey");
const credential: WebAuthnCredential = {
id: stored.id,
publicKey: stored.publicKey,
counter: stored.counter,
transports: stored.transports,
};
const verification = await verifyAuthenticationResponse({
response: body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
credential,
requireUserVerification: false,
});
if (!verification.verified) throw new Error("Authentication not verified");
await db.updateCounter(stored.id, verification.authenticationInfo.newCounter);
return stored.userId;
}
How to read this code
- Two ceremonies, four functions: each ceremony has an options step that creates a challenge and a verify step that checks the response. You must store the challenge between the two steps.
takeChallengeis single-use: it fetches and deletes the challenge in one step, so a replayed response fails.excludeCredentials: it stops a user from registering the same authenticator twice.residentKey: 'required': it requests a discoverable credential, which sign-in without a username needs.requireUserVerification: false: the library defaults totrue. I setfalsehere because I usepreferredand inspect the flag myself. If you want every sign-in to count as multi-factor, leave the default attrueand requestrequired.- Credential lookup by ID: in
finishAuthentication, you look up the stored passkey from the credential ID in the response, then check that the account matches the user handle if the response includes one. attestationType: 'none': it skips attestation, as section 5 recommends.
Browser side
import {
startRegistration,
startAuthentication,
browserSupportsWebAuthnAutofill,
} from "@simplewebauthn/browser";
export async function createPasskey() {
const optionsJSON = await (
await fetch("/api/passkeys/register/options", { method: "POST" })
).json();
const attResp = await startRegistration({ optionsJSON });
const res = await fetch("/api/passkeys/register/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(attResp),
});
return res.ok;
}
export async function signInWithPasskey(useAutofill: boolean) {
const optionsJSON = await (
await fetch("/api/passkeys/login/options", { method: "POST" })
).json();
const asseResp = await startAuthentication({
optionsJSON,
useBrowserAutofill: useAutofill,
});
const res = await fetch("/api/passkeys/login/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(asseResp),
});
return res.ok;
}
export async function startConditionalUI() {
if (await browserSupportsWebAuthnAutofill()) {
await signInWithPasskey(true);
}
}
Conditional UI: the autofill prompt
Conditional UI shows passkeys in the browser’s normal autofill dropdown on your username field. The user does not have to find a “Sign in with a passkey” button. The setup has three parts.
<input type="text" name="username" autocomplete="username webauthn" autofocus />
- The
autocompleteattribute: the field needs bothusernameandwebauthnas values. Theautofocusattribute makes the prompt appear when the page loads. - A pending request: the underlying call uses
mediation: 'conditional'. It stays pending and shows no UI by itself until the user picks a passkey from the autofill list. - Abort handling: web.dev advises aborting the pending request when you need to start another WebAuthn call, or when the user leaves the page. In SimpleWebAuthn,
useBrowserAutofill: truestarts the conditional request. The library prepares an abort signal automatically whenever you callstartRegistration()orstartAuthentication(), and it offers acancelCeremony()helper for manual cancellation. - Feature detection: the
browserSupportsWebAuthnAutofill()helper checks whether the browser can do it. The web.dev article usesgetClientCapabilities()and itsconditionalGetflag for the same purpose. - Fallback: if the user picks a password from the dropdown, your normal password flow continues.
Call startConditionalUI() once when the sign-in page loads, and keep a visible “Use a passkey” button for browsers without autofill support.
What the options look like
I ran generateRegistrationOptions on Node 24.22.0 with SimpleWebAuthn 14.1.0 to see the real output.
| Field | Value I observed |
|---|---|
rp |
{ name: "Example App", id: "example.com" } |
user.displayName |
empty string, because I did not pass one |
challenge |
43 base64url characters, which encodes 32 random bytes |
timeout |
60000 milliseconds |
attestation |
none |
authenticatorSelection |
residentKey: required, userVerification: preferred, and requireResidentKey: true |
pubKeyCredParams |
algorithms -48, -8, -7, and -257, in that order |
The algorithm surprise
The first algorithm in my output, -48, is ML-DSA-44, a post-quantum signature algorithm. SimpleWebAuthn’s source says its default list is EdDSA, ES256, and RS256, and that when the runtime supports post-quantum algorithms, ML-DSA-44 is included as the most preferred. Node 24.22.0 supports it, so the list started with it, and Node printed an experimental warning.
The COSE identifiers are -7 for ES256, -257 for RS256, -8 for EdDSA, and -48, -49, -50 for ML-DSA-44, ML-DSA-65, and ML-DSA-87. I confirmed these with the library’s COSEALG helper. For a predictable deployment, pin the list yourself and pass the same value to the registration verifier.
import { COSEALG } from "@simplewebauthn/server/helpers";
const supportedAlgorithmIDs = [COSEALG.ES256, COSEALG.RS256];
// Pass it to generateRegistrationOptions() and verifyRegistrationResponse().
I did not test whether any real authenticator accepts ML-DSA, so treat that part as something to watch. My article on post-quantum cryptography explains why those algorithms exist.
Offer a passkey at the right moment
The best time to ask is right after a successful sign-in, when the user is already convinced you are trustworthy. The browser package has a useAutoRegister option that tries to silently create a passkey with the password manager the user just signed in with. I did not test it, so try it in a staging environment before using it.
8. What the Server Must Verify
Official docs: WebAuthn Level 3, section 7.2, NIST SP 800-63B-4 Appendix B
A library does most of this for you, and you should still know what it checks. The specification lists the steps for verifying an authentication assertion. These are the ones that matter most.
| Check | Why it matters |
|---|---|
The client data type is webauthn.get |
Stops a registration response being replayed as a login. |
| The challenge equals the one you issued | Stops replay of an old response. |
| The origin is one you expect | Stops a response collected on another site from working on yours. |
| The RP ID hash matches your RP ID | Binds the signature to your domain. |
| The user present flag is set | Confirms a person interacted with the authenticator. |
| The user verified flag is set when you require it | Confirms the authenticator checked the person. Ignore the flag if you did not require it. |
| Backup flags are consistent | A credential that was not backup eligible must not claim to be, and the backup state must not be set without eligibility. |
| The signature is valid for the stored public key | The core proof of possession. |
| The signature counter rule | If either the new or the stored counter is nonzero, the new counter should be greater. Otherwise the authenticator may be cloned. |
| The user handle matches the account | For discoverable credentials, confirms the credential belongs to the account you identified. |
What the library does not do for you
- Challenge lifecycle: you store, expire, and delete challenges.
- Account lookup: you decide which user a credential belongs to.
- Counter persistence: you save the new counter after each success.
- Policy: you decide what to do with the backup flags, the user verification flag, and the device type.
- Session creation: after verification you create the session, and section 12 explains how.
A note on counters
Many synced passkeys always report a counter of zero. The specification’s rule only treats a stale counter as a warning sign when one of the values is nonzero. Do not lock out users because their counter stayed at zero.
9. Keeping Passkeys in Sync
Official docs: Chrome: the Signal API, web.dev: related origin requests
A passkey lives in two places: the user’s authenticator and your database. They can drift apart. A user deletes a passkey on your server, but the old one still appears in their autofill list, and tapping it fails.
The WebAuthn Level 3 signal API fixes that by letting your site tell the authenticator what happened.
signalUnknownCredential: tells the authenticator that a credential ID no longer exists on your server. Use it when a sign-in attempt names a credential you do not recognize.signalAllAcceptedCredentials: sends the complete list of valid credential IDs for a user. According to Chrome’s documentation, passkeys missing from the list are marked hidden and not deleted immediately.signalCurrentUserDetails: updates the name and display name that appear next to a passkey.
Support and limits
- Browsers: Chrome’s documentation lists Chrome 132 and Edge 132, and newer snapshots list Safari 26. Firefox is listed as not supported.
- Best effort: signals are not guaranteed to reach every authenticator, and the provider decides how to act on them.
- In code: SimpleWebAuthn’s browser package exports a
sendSignal()method that accepts the unknown-credential, all-accepted-credentials, and current-user-details options. Its own documentation warns that sending a signal does not guarantee the authenticator receives it.
A sensible pattern is to call signalAllAcceptedCredentials after each sign-in and after any change to the user’s passkey list, and to call signalUnknownCredential when your server answers that a credential is unknown.
10. TOTP: Authenticator App Codes
Official docs: RFC 6238 (TOTP), RFC 4226 (HOTP), OWASP Multifactor Authentication Cheat Sheet
TOTP is the six-digit code that changes every 30 seconds in apps such as Google Authenticator, Microsoft Authenticator, and password managers. It is weaker than a passkey, because a phishing site can ask for the code and relay it in real time. It is still much stronger than a text message, and it works everywhere, so it is a reasonable fallback.
How it works
- At setup, your server creates a random secret and shows it to the user as a QR code or a text string.
- The app stores the secret: From then on, the app and your server both compute a code from the secret and the current time.
- At sign-in, the user types the current code, and your server computes the same code and compares.
Both sides use HMAC with the secret and a counter derived from the clock. RFC 4226 defines the counter version, called HOTP. RFC 6238 turns it into a time version by using the number of 30-second steps since 1970 as the counter.
The implementation
I wrote this in TypeScript with only Node’s built-in crypto module, and checked it against the official test vectors.
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
export function base32Encode(buf: Uint8Array): string {
let bits = 0;
let value = 0;
let out = "";
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += B32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) out += B32[(value << (5 - bits)) & 31];
return out;
}
export function base32Decode(str: string): Buffer {
let bits = 0;
let value = 0;
const out: number[] = [];
for (const ch of str.replace(/=+$/, "").toUpperCase()) {
const idx = B32.indexOf(ch);
if (idx === -1) throw new Error("Invalid base32 character");
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 255);
bits -= 8;
}
}
return Buffer.from(out);
}
// RFC 4226 recommends a 160-bit (20-byte) secret.
export function generateSecret(): string {
return base32Encode(randomBytes(20));
}
export function hotp(
secret: Buffer,
counter: number,
digits = 6,
algorithm = "sha1",
): string {
const msg = Buffer.alloc(8);
msg.writeBigUInt64BE(BigInt(counter));
const hmac = createHmac(algorithm, secret).update(msg).digest();
const offset = hmac[hmac.length - 1] & 0x0f;
const code =
((hmac[offset] & 0x7f) << 24) |
(hmac[offset + 1] << 16) |
(hmac[offset + 2] << 8) |
hmac[offset + 3];
return String(code % 10 ** digits).padStart(digits, "0");
}
export function totp(
secretBase32: string,
nowMs = Date.now(),
step = 30,
digits = 6,
algorithm = "sha1",
): string {
const counter = Math.floor(nowMs / 1000 / step);
return hotp(base32Decode(secretBase32), counter, digits, algorithm);
}
// Returns the matched time step, or null. Accepts the previous and next step for clock drift.
export function verifyTotp(
secretBase32: string,
token: string,
nowMs = Date.now(),
window = 1,
step = 30,
): number | null {
if (!/^\d{6}$/.test(token)) return null;
const secret = base32Decode(secretBase32);
const current = Math.floor(nowMs / 1000 / step);
for (let i = -window; i <= window; i++) {
const expected = Buffer.from(hotp(secret, current + i));
if (timingSafeEqual(expected, Buffer.from(token))) return current + i;
}
return null;
}
export function otpauthUri(
issuer: string,
account: string,
secretBase32: string,
): string {
const label = encodeURIComponent(`${issuer}:${account}`);
return `otpauth://totp/${label}?secret=${secretBase32}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=30`;
}
Test results
I ran the code against the published vectors. RFC 6238 Appendix B uses the secret 12345678901234567890 with SHA-1 and eight digits, and its codes match for every time value I tried.
| Unix time | Expected (8 digits) | My result | Six-digit result |
|---|---|---|---|
| 59 | 94287082 | Pass | 287082 |
| 1111111109 | 07081804 | Pass | 081804 |
| 1111111111 | 14050471 | Pass | 050471 |
| 1234567890 | 89005924 | Pass | 005924 |
| 2000000000 | 69279037 | Pass | 279037 |
| 20000000000 | 65353130 | Pass | 353130 |
The HOTP vectors from RFC 4226 Appendix D also pass. A code from one step ago is accepted and a code from two steps ago is rejected, which matches the window setting.
Rules for a safe TOTP flow
- Confirm before enabling: after showing the QR code, make the user enter a valid code before you mark the factor active. That proves their app has the secret.
- Store the secret encrypted: OWASP advises storing seeds encrypted, ideally with keys in a hardware security module or key management service, and never returning the seed after enrollment.
- Accept a narrow window: the current step and at most one previous step. My function uses a window of one on each side, so adjust it if you only want the previous step.
- Reject replays: OWASP says to reject a code that was already accepted for that user, even if it is still inside the window.
verifyTotpreturns the matched step so you can store it aslast_used_stepand refuse anything at or below it. - Rate limit: put strict attempt limits on verification. NIST’s baseline is no more than 100 consecutive failures before disabling the authenticator, and lower is better for a web app.
- Use a good secret: NIST requires at least 112 bits. RFC 4226 recommends 160 bits, which is what
generateSecretmakes. - Re-enroll after exposure: if a seed might have leaked, make the user enroll a new one. Changing the password does not change the seed.
- Do not use SMS as a second TOTP: a code sent by text is a different, weaker mechanism.
11. Recovery Codes and Account Recovery
Official docs: OWASP Multifactor Authentication Cheat Sheet, CyberInsider: new downgrade attack on FIDO passkeys
Recovery is where strong authentication goes to die. If a user can bypass a passkey by clicking “I lost my device” and answering an email, then an attacker can do the same, and the passkey protected nothing.
OWASP states the principle directly. Processes that let users bypass or reset multi-factor authentication may be exploitable by attackers, and fallback mechanisms must not be weaker than the primary methods.
Recovery codes
Single-use recovery codes are the standard answer. You generate a set when the user enables a second factor, show them once, and store only hashes.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { base32Encode } from "./totp.js";
// Show these once to the user. Store only the hashes.
export function generateRecoveryCodes(count = 10): {
codes: string[];
hashes: string[];
} {
const codes = Array.from({ length: count }, () => {
const raw = base32Encode(randomBytes(10)); // 80 bits, 16 characters
return raw.match(/.{4}/g)!.join("-");
});
return { codes, hashes: codes.map(hashRecoveryCode) };
}
export function hashRecoveryCode(code: string): string {
const normalized = code.replace(/[\s-]/g, "").toUpperCase();
return createHash("sha256").update(normalized).digest("hex");
}
// Returns the index of the matching unused hash, or -1. Mark that code used in the same transaction.
export function matchRecoveryCode(
input: string,
unusedHashes: string[],
): number {
const candidate = Buffer.from(hashRecoveryCode(input), "hex");
let found = -1;
unusedHashes.forEach((h, i) => {
const stored = Buffer.from(h, "hex");
if (
stored.length === candidate.length &&
timingSafeEqual(stored, candidate)
)
found = i;
});
return found;
}
I ran this code. It produced ten unique codes in the form xxxx-xxxx-xxxx-xxxx, accepted a code typed in lowercase without dashes, and rejected a wrong one. The codes carry 80 bits of randomness, so a fast hash is acceptable, and you must still rate limit attempts.
- Single use: mark a code used in the same database transaction that accepts it.
- Show once: present the codes after enrollment and encourage the user to store them somewhere safe.
- Regenerate on demand: let the user create a new set, which invalidates the old one.
- Notify: send an out-of-band message whenever a recovery code is used.
Other recovery options
OWASP lists several, and each has a cost.
| Option | Strength | Risk |
|---|---|---|
| A second registered passkey | Strong, and it keeps phishing resistance | The user must create it before they need it |
| Recovery codes | Offline and simple | Users lose them or store them insecurely |
| A one-time link to the registered email | Familiar | Only as strong as the email account, and NIST bans email as out-of-band authentication |
| A verified support process | Handles hard cases | A prime social engineering target |
Rules for recovery
- Make recovery as strong as sign-in: an email link alone should not bypass a passkey on a high-value account.
- Require re-authentication to change factors: adding or removing a factor should need an existing factor, not just an active session.
- Notify on every factor change: send an email or push message to the user outside the session whenever a factor is added, removed, or reset.
- Add a delay for risky recovery: a waiting period with notifications gives the real owner time to object.
- Log recovery events: they are a favorite target for attackers.
Downgrade attacks
Attackers have learned to go around passkeys by pushing users toward the fallback. Proofpoint’s research, as reported by security news outlets, showed that an adversary-in-the-middle phishing kit can spoof a browser that a platform does not support for passkeys, so the service disables the passkey option and offers a weaker method. The attack does not break origin binding. It exploits the server’s fallback policy. Proofpoint said it had not seen the technique in real campaigns at the time of its research.
The defense is a policy choice. Restrict fallback methods for accounts that have a passkey, be careful with “try another way” prompts, and keep recovery on strong channels.
12. Sessions and Step-Up Authentication
Official docs: OWASP Multifactor Authentication Cheat Sheet
Strong sign-in only helps if the session that follows is protected as well.
After a successful sign-in
- Create a fresh session identifier: never reuse a pre-login session ID, so an attacker cannot plant one.
- Set cookie flags:
HttpOnly,Secure, and a suitableSameSitevalue. - Keep lifetimes short for sensitive apps: and offer a “remember this device” choice only with clear limits.
- Record how the user authenticated: store whether it was a passkey with user verification, a password plus TOTP, or a recovery code. Later decisions can use it.
Step-up for sensitive actions
OWASP says the most important place to require multi-factor authentication is at login, and it recommends step-up prompts for sensitive actions such as changing the password, changing the email address, disabling multi-factor authentication, or elevating to an administrator.
- Require recent authentication: ask for a fresh passkey tap when the last strong authentication is older than your threshold.
- Request
userVerification: 'required': for step-up ceremonies, and verify the flag on the server. - Do not trust the session alone: NIST and OWASP both warn against changing factors based only on an active session.
Rate limiting everywhere
Limit attempts per account and per IP address for passwords, TOTP, recovery codes, and passkey options requests. Add a delay or a challenge after repeated failures.
13. Attacks and Defenses
Official docs: CISA phishing-resistant MFA fact sheet
No method is perfect. This table shows what each attack targets and what stops it.
| Attack | What it does | What helps |
|---|---|---|
| Credential phishing | Tricks users into typing a password on a fake site. | Passkeys, because origin binding gives a fake site nothing useful. |
| Adversary-in-the-middle proxy | Relays a real login page and steals passwords, codes, and sessions. | Passkeys. TOTP and SMS do not stop it. |
| Downgrade to a weaker method | Forces the user onto SMS, TOTP, or recovery. | Restrict fallbacks for accounts with passkeys. |
| SIM swap and SS7 attacks | Redirect text messages to the attacker. | Stop using SMS for anything important. |
| Push bombing | Spams approval prompts until the user taps accept. | Avoid approval-only push, or use number matching. NIST no longer accepts approval-only prompts. |
| Credential stuffing | Replays leaked passwords against your login. | Remove passwords for passkey users, and rate limit. |
| Session theft | Steals the cookie after login. | Short sessions, secure cookies, and step-up for sensitive actions. |
| Weak recovery | Uses a support desk or an email link to take over an account. | Strong recovery, re-authentication, notifications, and delays. |
| Malware on the device | Acts as the user after they authenticate. | Device security. Passkeys do not fix a compromised device. |
| Sync account compromise | Takes over the password manager or platform account that syncs passkeys. | Encourage strong accounts with multi-factor protection. NIST requires AAL2-equivalent protection for sync fabric access. |
The honest limit of passkeys is that they protect the sign-in. They do not fix a compromised device, a careless recovery flow, or a stolen session.
14. Testing and Rollout
Official docs: SimpleWebAuthn documentation, FIDO Passkey Index 2026
What to test
- Unit tests: run your TOTP code against the RFC vectors, as I did, and test recovery code single use.
- Ceremony tests: register, sign in, and sign in with a wrong challenge, a wrong origin, a replayed response, and an unknown credential.
- Browsers and devices: test Chrome, Safari, Firefox, and Edge on desktop and mobile, with platform authenticators and a hardware key.
- Virtual authenticators: Chrome’s developer tools and browser automation tools can simulate a security key. I did not use one for this article, so check the current documentation of your test framework.
- Failure paths: a user cancels the prompt, the browser lacks support, the passkey was deleted, and the clock is off for TOTP.
Roll out in stages
- Internal users first: Staff will report problems quickly and tolerate rough edges.
- Offer passkey creation after sign-in to a small percentage of users, then widen it.
- Add autofill sign-in so returning users see their passkey immediately.
- Make passkeys the prominent path and demote passwords.
- Remove weak fallbacks for accounts that have passkeys, as your risk allows.
What to measure
| Metric | Why it matters |
|---|---|
| Passkey enrollment rate | Shows whether users find and accept the prompt. |
| Passkey sign-in success rate | The FIDO index reports 93 percent across participants, which gives you a benchmark. |
| Fallback rate after passkey enrollment | Reveals downgrade attempts and confusing flows. |
| Recovery requests | A spike signals lost-device problems or an attack. |
| Support tickets about sign-in | Shows real friction. |
| Time to sign in | The index reports passkey sign-ins about 27 seconds faster on average. |
15. Libraries and Providers
Official docs: SimpleWebAuthn, Supabase: passkeys beta
You can build this yourself with a good library, or use a provider. Both are valid, and the right choice depends on how much control you need.
Libraries
| Library | Language | Notes |
|---|---|---|
| SimpleWebAuthn server and browser | TypeScript | MIT licensed. Server 14.1.0 on November 6, 2026, requiring Node 22 or later. I tested the code above with it. |
webauthn on PyPI (py_webauthn) |
Python | Version 3.0.1 is the latest on PyPI. I did not test it. |
Other languages have maintained WebAuthn libraries too. Pick one with recent releases and a clear security policy, and read its issue tracker before trusting it.
Hosted providers
I checked a few providers that small teams commonly use.
- Supabase Auth: passkeys entered beta on May 28, 2026, using discoverable credentials. The API is experimental, requires an explicit opt-in, and may change without notice. Registration needs an existing session, and the SDK methods include
registerPasskey(),signInWithPasskey(), and anauth.passkeynamespace with list, update, and delete. The relying party ID must be your bare domain, and up to five origins are allowed. - Firebase Authentication: I found no official documentation for passkeys. Community extensions exist, and a pull request to Firebase’s emulator mentions a private preview, but I could not confirm any current official support. Check Firebase’s release notes before you plan around it.
- Auth0, Clerk, and Amazon Cognito: comparisons I read describe passkey support for all three. I did not verify their documentation, so read it yourself.
Build or buy
Build your own if you need full control, have a strong team, and can maintain the code. Use a provider if you want less code to secure, as long as its passkey support is stable and exportable. Whatever you choose, check how you would migrate away. Credential portability between passkey providers is still being specified. The FIDO Alliance has working drafts of a credential exchange protocol and format, and I found no confirmation that they are final.
16. Common Mistakes
- Treating passkeys as a fancy password field: The design questions in section 5 matter more than the widget.
- Skipping the origin and RP ID checks: They are the heart of phishing resistance. Let the library enforce them.
- Reusing or not expiring challenges: A stored, single-use, short-lived challenge is mandatory.
- Failing to inspect the user verification flag: Without it you cannot tell multi-factor from single-factor.
- Locking users out over a zero counter: Many synced passkeys always report zero.
- Keeping SMS or email as an easy bypass: The weakest recovery path sets your real security level.
- Storing TOTP seeds in plaintext: Encrypt them, and never show them again.
- Accepting a TOTP code twice: Reject replays inside the time window.
- Showing recovery codes repeatedly: Show them once, store hashes, and let users regenerate.
- Forgetting to tell users: Notify them whenever a factor is added, removed, or reset.
- Not letting users manage passkeys: Provide a list with names, last used times, and a delete button.
- Assuming devices are safe: A compromised browser can act as the user after sign-in.
17. Frequently Asked Questions
What is a passkey?
It is a public-key credential, usually synced between a user’s devices by a password manager or platform account. Your server stores the public key, and the user’s device holds the private key.
Are passkeys the same as WebAuthn?
Passkeys are a user-friendly term for discoverable WebAuthn credentials. WebAuthn is the browser API underneath. The W3C published its Level 3 specification as a Recommendation on August 25, 2026.
Do passkeys replace two-factor authentication?
A passkey with user verification is multi-factor authentication on its own. The device is something you have, and the biometric or PIN is something you are or know. If the user was not verified, NIST says to treat it as single-factor.
Can a phishing site steal a passkey?
It cannot get a usable signature, because the authenticator signs only for the domain where the credential was created. A phishing site can still try to push the user onto a weaker fallback, so protect your fallbacks.
What if the user loses their phone?
A synced passkey usually survives, because it lives in their password manager or platform account. For other cases, a second registered passkey or recovery codes are the strong answers. Design this before launch.
Are synced passkeys secure enough?
For most apps, yes. NIST allows syncable authenticators at AAL2 under conditions, and does not allow them at AAL3 because syncing makes the key exportable. High-assurance systems can require device-bound credentials by checking the backup eligible flag.
Do I still need passwords?
During a migration, probably. Many apps keep passwords as an option while users move to passkeys. The long-term goal is to make passkeys the default and passwords a rare fallback.
Is TOTP still worth offering?
Yes, as a fallback for users and devices without passkey support. It is weaker than a passkey because phishing kits can relay codes. It is much stronger than SMS.
Is SMS acceptable?
NIST classes phone-network codes as a restricted authenticator, and CISA calls SMS and voice a last resort. If you must keep it, document the risk, rate limit, and consider signals such as recent SIM changes.
How many passkeys can a user have?
Allow several per account. Providers differ, and Clerk’s documentation, as I saw it summarized, caps accounts at 10. Let users name and delete them.
Which browsers support this?
The major browsers support WebAuthn. Conditional UI and the signal API vary, and Chrome’s documentation lists Chrome and Edge 132 and Safari 26 for signals, with no Firefox support. Test the features you depend on.
Does my app need attestation?
Usually not, for most apps. Leave it at none unless you have a policy that depends on the authenticator model.
Can I use a passkey as a second factor after a password?
Yes, you can do that. In that case SimpleWebAuthn’s documentation suggests setting user verification to discouraged, because the password already counts as a factor. Remember that an unverified authenticator is single-factor under NIST’s rules.
How do I choose signature algorithms in WebAuthn?
The options list tells the authenticator which signature algorithms you accept, using COSE identifiers: -7 for ES256, -257 for RS256, and -8 for EdDSA. Pin the list so deployments behave the same everywhere.
What should I do first?
Add passkey creation after sign-in, keep your existing login as a fallback, and fix your recovery flow so it is not weaker than the passkey.
18. Conclusion
Passkeys solve the problem that kept two-factor authentication from stopping phishing. The secret never leaves the device, and the credential only works on your domain. With WebAuthn Level 3 finalized, solid libraries, and real adoption numbers behind it, there is little reason to build a new sign-in flow without them.
The code is the easy part. The hard parts are design choices: what the passkey is allowed to do, how users recover, and which fallbacks you keep. Attackers have already shifted to those fallbacks, so make recovery as strong as sign-in, notify users about every change, and verify the flags that tell you how a user authenticated.
Start small and measure. Offer a passkey after sign-in, add autofill, measure enrollment and success, and tighten the fallbacks as your users move over. Standards and products in this area keep changing, so treat this article as a map as of late November 2026.
19. References
Standards and guidance
- W3C: Web Authentication Level 3 (Recommendation, August 25, 2026)
- NIST SP 800-63B-4: authentication and authenticator management
- CISA: implementing phishing-resistant MFA (October 2022)
- OWASP: Multifactor Authentication Cheat Sheet
- RFC 4226: HOTP
- RFC 6238: TOTP
Adoption and research
- FIDO Alliance: Passkey Index 2026
- FIDO Alliance: State of Passkeys 2026
- CyberInsider: new downgrade attack on FIDO passkeys (Proofpoint research)
- BleepingComputer: attempts to downgrade FIDO2 authentication (PoisonSeed)
Implementation
- SimpleWebAuthn
- web.dev: passkey form autofill
- web.dev: related origin requests
- Chrome: keep passkeys consistent with the Signal API
- Supabase: passkeys for Supabase Auth (beta)