Passkeys: Passwordless Authentication with WebAuthn and FIDO2


Passwords have the same problems they have always had. People reuse them, they leak in breaches, and they get typed into phishing sites. Adding one-time codes by SMS or an authenticator app helps against stolen passwords, but it doesn't stop phishing: a fake site can ask for the code and relay it to the real site in real time. In 2025, Japanese online brokerages were hit by a wave of phishing-driven account takeovers, and the industry has since moved toward requiring phishing-resistant MFA. Passkeys are the most practical way to provide it.

This post explains how passkeys work, then walks through a working implementation in TypeScript: registration, login, autofill, automatic upgrades from passwords and the Signal API. It finishes with the security details that are easy to get wrong. Browser support data and library versions are as of October 2026.

What a passkey is

A passkey is a public/private key pair bound to one website.

  • The private key stays in an authenticator: the platform's credential manager (iCloud Keychain, Google Password Manager, Windows Hello, or a third-party manager such as 1Password) or a hardware security key. It never leaves the authenticator.
  • The public key is stored on your server.
  • To log in, the server sends a random challenge, and the authenticator signs it after the user unlocks it with a fingerprint, face or PIN. The server checks the signature with the public key.

Two properties follow from this design:

  1. Phishing resistance. The browser binds every passkey to the site's RP ID (the domain, such as example.com) and writes the real origin into the signed data. A passkey for example.com can't be used on examp1e.com, and the user can't be tricked into using it there, because the browser simply won't offer it.
  2. Nothing useful to steal from the server. The database holds only public keys. If it leaks, attackers can't log in with it, and there is nothing shared to reuse on other sites.

The terms

| Term | Meaning | | - | - | | FIDO2 | The umbrella name for WebAuthn (the W3C browser API) plus CTAP2 (the FIDO Alliance protocol between a browser and an external authenticator) | | Relying Party (RP) | Your service, which verifies the passkey | | RP ID | The domain the passkey is bound to. It is effectively permanent, so choose carefully. | | Discoverable credential | A passkey stored together with the user's account information, so the user can log in without typing a username. Passkeys are always discoverable. | | User verification (UV) | The authenticator checking that the right person is present (biometrics or PIN). With UV, a passkey on its own counts as multi-factor: something you have plus something you are or know. | | Synced vs. device-bound | Synced passkeys are backed up and synced through the credential manager's cloud. Device-bound passkeys, typically on security keys, never leave the hardware. | | Hybrid | Using a phone's passkey to sign in on another device, by scanning a QR code. Bluetooth proximity is checked so the flow can't be relayed remotely. |

How it works

Registration

  1. The server creates options: the RP ID, the user's ID and name, a random challenge, and the passkeys the user already has (so they aren't registered twice).
  2. The browser calls navigator.credentials.create(). The authenticator verifies the user and creates a new key pair.
  3. The browser returns the public key, the credential ID and the signed client data.
  4. The server checks the challenge, origin, RP ID and flags, then stores the public key, credential ID, signature counter and transports.

Authentication

  1. The server creates a challenge.
  2. The browser calls navigator.credentials.get(). The user picks a passkey and unlocks it.
  3. The authenticator signs the authenticator data together with a hash of the client data, which includes the challenge and the origin.
  4. The server finds the stored public key by credential ID, verifies the signature, challenge, origin and RP ID, and creates a session.

Implementation: the browser side

Modern browsers can turn the server's JSON options into WebAuthn objects and back without any base64url helper code: PublicKeyCredential.parseCreationOptionsFromJSON(), parseRequestOptionsFromJSON() and credential.toJSON() are available in Chrome 129+, Firefox 119+ and Safari 18.4+. If you need to support older browsers, @simplewebauthn/browser wraps the same flow.

Registering a passkey

async function postJSON<T>(url: string, body?: unknown): Promise<T> {
  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body ?? {}),
  });
  if (!response.ok) {
    throw new Error(`${url} failed with ${response.status}`);
  }
  return response.json() as Promise<T>;
}
 
async function registerPasskey(): Promise<void> {
  const optionsJSON = await postJSON<PublicKeyCredentialCreationOptionsJSON>("/webauthn/register/options");
  const credential = await navigator.credentials.create({
    publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(optionsJSON),
  });
  if (!(credential instanceof PublicKeyCredential)) {
    throw new Error("No passkey was created");
  }
  await postJSON("/webauthn/register/verify", credential.toJSON());
}

Logging in with autofill (conditional UI)

The best login experience shows passkeys in the browser's autofill menu on the username field. Add webauthn to the field's autocomplete attribute:

<input type="text" name="username" autocomplete="username webauthn" />

Then start a conditional request when the page loads. It stays pending until the user picks a passkey from the autofill menu:

async function startPasskeyAutofill(): Promise<void> {
  if (!(await PublicKeyCredential.isConditionalMediationAvailable())) {
    return;
  }
  const optionsJSON = await postJSON<PublicKeyCredentialRequestOptionsJSON>("/webauthn/login/options");
  const credential = await navigator.credentials.get({
    mediation: "conditional",
    publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(optionsJSON),
  });
  if (!(credential instanceof PublicKeyCredential)) {
    return;
  }
 
  const result = await postJSON<{ ok: boolean; unknownCredential?: boolean }>(
    "/webauthn/login/verify",
    credential.toJSON(),
  );
  if (result.unknownCredential) {
    await PublicKeyCredential.signalUnknownCredential?.({ rpId: optionsJSON.rpId ?? location.hostname, credentialId: credential.id });
  }
  if (result.ok) {
    location.assign("/");
  }
}

This works for users with and without passkeys. Users without passkeys see nothing new and type their password as usual. That is what makes a gradual rollout possible.

The Signal API: keeping credential managers in sync

A common annoyance: a user deletes a passkey in your account settings, but the passkey stays in their password manager and keeps failing. The Signal API lets the RP tell the credential manager what changed:

  • signalUnknownCredential(): "this credential ID doesn't exist on my side" (used in the code above).
  • signalAllAcceptedCredentials(): "these are the only valid credential IDs for this user".
  • signalCurrentUserDetails(): "this user's name or display name has changed".

They are supported in Chrome 132+ and Safari 26, but not yet in Firefox. That is why the code uses optional calls (?.).

Automatic upgrades from passwords (conditional create)

When a user has just signed in with a password from their password manager, the browser can create a passkey silently in that same manager without showing a dialog. Call this on the page the user lands on after logging in:

async function offerAutomaticPasskeyUpgrade(): Promise<void> {
  const capabilities = await PublicKeyCredential.getClientCapabilities?.();
  if (!capabilities?.conditionalCreate) {
    return;
  }
  const optionsJSON = await postJSON<PublicKeyCredentialCreationOptionsJSON>("/webauthn/register/options");
  try {
    const credential = await navigator.credentials.create({
      mediation: "conditional",
      publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(optionsJSON),
    } as CredentialCreationOptions); // TypeScript's DOM lib does not declare `mediation` for create() yet.
    if (credential instanceof PublicKeyCredential) {
      await postJSON("/webauthn/register/verify", credential.toJSON());
    }
  } catch {
    // Conditional create is opportunistic: the browser may decline silently and the user just keeps their password.
  }
}

getClientCapabilities() (Chrome 133+, Firefox 135+, Safari 17.4+) is the correct way to detect features like this one. Don't rely on user-agent sniffing.

One caveat on the server: a passkey created this way usually has the User Presence flag unset, because no dialog was shown. With SimpleWebAuthn, pass requireUserPresence: false to verifyRegistrationResponse() only for this flow.

Implementation: the server side

On the server I use SimpleWebAuthn (@simplewebauthn/server v14, which needs Node 22 or later). WebAuthn verification involves CBOR, COSE keys, attestation formats and certificate chains, so use a well-maintained library rather than writing your own.

In the code below, User, passkeyStore and challengeStore stand in for your own user model and storage, for example a database table for passkeys and a key-value store with expiry for challenges.

import {
  generateAuthenticationOptions,
  generateRegistrationOptions,
  verifyAuthenticationResponse,
  verifyRegistrationResponse,
  type AuthenticationResponseJSON,
  type CredentialDeviceType,
  type RegistrationResponseJSON,
  type WebAuthnCredential,
} from "@simplewebauthn/server";
 
const RP_NAME = "Example Inc.";
const RP_ID = "example.com";
const EXPECTED_ORIGIN = "https://example.com";
const CHALLENGE_TTL_MS = 5 * 60 * 1000;
 
type StoredPasskey = WebAuthnCredential & {
  userId: string;
  deviceType: CredentialDeviceType;
  backedUp: boolean;
};
 
export async function createRegistrationOptions(user: User) {
  const existingPasskeys = await passkeyStore.listByUser(user.id);
  const options = await generateRegistrationOptions({
    rpName: RP_NAME,
    rpID: RP_ID,
    userName: user.email,
    userID: user.webauthnUserId,
    attestationType: "none",
    excludeCredentials: existingPasskeys.map((passkey) => ({ id: passkey.id, transports: passkey.transports })),
    authenticatorSelection: { residentKey: "required", userVerification: "required" },
  });
  await challengeStore.save(`register:${user.id}`, options.challenge, CHALLENGE_TTL_MS);
  return options;
}
 
export async function finishRegistration(user: User, response: RegistrationResponseJSON) {
  const expectedChallenge = await challengeStore.consume(`register:${user.id}`);
  if (!expectedChallenge) {
    throw new Error("Registration challenge expired or already used");
  }
 
  const { verified, registrationInfo } = await verifyRegistrationResponse({
    response,
    expectedChallenge,
    expectedOrigin: EXPECTED_ORIGIN,
    expectedRPID: RP_ID,
  });
  if (!verified) {
    throw new Error("Passkey registration could not be verified");
  }
 
  const { credential, credentialDeviceType, credentialBackedUp } = registrationInfo;
  await passkeyStore.save({
    id: credential.id,
    userId: user.id,
    publicKey: credential.publicKey,
    counter: credential.counter,
    transports: credential.transports,
    deviceType: credentialDeviceType,
    backedUp: credentialBackedUp,
  });
}
 
export async function createLoginOptions(sessionId: string) {
  const options = await generateAuthenticationOptions({ rpID: RP_ID, userVerification: "required" });
  await challengeStore.save(`login:${sessionId}`, options.challenge, CHALLENGE_TTL_MS);
  return options;
}
 
export async function finishLogin(sessionId: string, response: AuthenticationResponseJSON) {
  const expectedChallenge = await challengeStore.consume(`login:${sessionId}`);
  if (!expectedChallenge) {
    throw new Error("Login challenge expired or already used");
  }
 
  const passkey = await passkeyStore.findById(response.id);
  if (!passkey) {
    return { ok: false, unknownCredential: true } as const;
  }
 
  const { verified, authenticationInfo } = await verifyAuthenticationResponse({
    response,
    expectedChallenge,
    expectedOrigin: EXPECTED_ORIGIN,
    expectedRPID: RP_ID,
    credential: passkey,
  });
  if (!verified) {
    return { ok: false } as const;
  }
 
  await passkeyStore.updateAfterLogin(passkey.id, authenticationInfo.newCounter, new Date());
  return { ok: true, userId: passkey.userId } as const;
}

Here is why each setting is what it is.

  • challengeStore.consume(): a challenge must be random, stored on the server, single-use and short-lived. Deleting it once it's used is what stops replay attacks.
  • userID: user.webauthnUserId: this is the user handle. It must be random bytes, not an email address or other personal data, because it is stored in the authenticator. It also has to stay the same for each user. If you generate a new one each time, the user's password manager ends up with duplicate passkeys for the same account.
  • residentKey: "required": required for username-less login and autofill.
  • userVerification: "required": makes the passkey a full second factor on its own. SimpleWebAuthn's verify* functions require UV by default, and that default should stay.
  • attestationType: "none": attestation proves which authenticator model created the key. Consumer services almost never need it, and requesting it adds friction and privacy concerns. Enterprise services that only allow approved security keys are the exception.
  • excludeCredentials: stops the same authenticator from being registered twice for one account.
  • The counter: synced passkeys usually always report 0, so a counter that doesn't increase isn't, on its own, a sign of cloning.

Security details that are easy to get wrong

1. Account recovery is now the weakest link. Passkeys remove phishing from the login step. If "lost your passkey?" falls back to an SMS code or an email link, attackers will use that route instead. Encourage users to register at least two passkeys (for example a phone plus a laptop or a security key), and treat recovery as a high-risk flow that deserves extra checks.

2. The RP ID is close to permanent. A passkey is bound to its RP ID for life. Moving from example.co.jp to example.com later would strand every passkey. Choose the registrable domain on purpose. If you need several domains, Related Origin Requests let you list permitted origins in /.well-known/webauthn.

3. Verify origin and RP ID on the server, every time. Libraries do this for you, but only if you pass the right expectedOrigin and expectedRPID. Never take them from the request itself.

4. Synced passkeys move the trust boundary. A synced passkey is as safe as the cloud account that syncs it (Apple, Google, the password manager). For most consumer services that is a big improvement over passwords. NIST SP 800-63B-4 accepts syncable authenticators at AAL2. For high-assurance cases, consider requiring device-bound credentials and checking the backedUp flag.

5. Keep the library up to date. In 2026 alone, SimpleWebAuthn fixed several security advisories in attestation certificate chain and revocation handling. WebAuthn verification is cryptographic code with many edge cases, so dependency updates are not optional.

6. Post-quantum cryptography is starting to arrive. SimpleWebAuthn v14 added support for ML-DSA (post-quantum signatures) as passkey algorithms in runtimes that support it, and prefers ML-DSA-44 at registration. Authenticators that support it are only beginning to appear, but because the library handles algorithm negotiation, an RP can be ready for them without code changes.

Rolling it out

Switching every user to passwordless overnight isn't realistic. A staged plan works better:

  1. Make it optional. Let users add a passkey from account settings.
  2. Turn on autofill. Users who have passkeys can log in in one step, and nobody else's flow changes.
  3. Upgrade automatically. After a password login, try conditional create, and also offer a "Create a passkey?" prompt.
  4. Make it the default. Show passkey sign-in first for new users, and keep the password path only as a fallback.
  5. Tighten recovery. As passkey coverage grows, move recovery away from phishable channels.

Summary

  • A passkey is a public/private key pair bound to one domain. The browser enforces that binding, which is what makes passkeys resistant to phishing, unlike passwords and OTPs.
  • The server stores only public keys, so a database leak doesn't expose anything attackers can log in with.
  • With JSON helpers in the browser and SimpleWebAuthn on the server, the implementation is short. Autofill, conditional create and the Signal API make the experience smooth.
  • The real work is in the surrounding details: challenge handling, a random user handle, the choice of RP ID, account recovery and keeping dependencies current.

References


tsukihime_animated_avatar.gif

By Marko Leinikka

09 July 2026 at 03:00

Word count: 2238
10 min read