How-To Guide

How to Implement Passkeys with WebAuthn

Add passkey sign-in with WebAuthn: registration and authentication ceremonies, credential storage, and the checks that prevent phishing.

On this page

  1. Introduction
  2. How WebAuthn Works
  3. The Registration Ceremony
  4. The Authentication Ceremony
  5. What the Server Must Verify
  6. Storing Credentials and Recovery
  7. Common Pitfalls and Conclusion

Introduction

Passwords are the weakest link in authentication: they are phished, reused, leaked and brute-forced. Passkeys replace them with public-key credentials held in the user’s device or password manager. The device keeps the private key; your server stores only the public key. Authentication is a signature over a server-issued challenge, so there is no shared secret to steal and no password to phish. WebAuthn is the browser API for creating and using these credentials, and this tutorial builds the registration and authentication ceremonies end to end.

How WebAuthn Works

WebAuthn is a public-key protocol. At registration, the authenticator generates a key pair, keeps the private key, and gives the server the public key along with a credential id. At authentication, the server sends a random challenge, the authenticator signs it with the private key, and the server verifies the signature against the stored public key.

The challenge is the anti-replay mechanism: it is random, single-use and time-bounded. Because the signature covers the challenge, the origin and the authenticator data, a signature captured from one site cannot be replayed on another, and a signature from one login cannot be reused. That is what makes passkeys phishing-resistant.

The private key never leaves the authenticator, which may be a platform authenticator built into a device, a roaming key on a USB dongle, or a synced credential in a password manager. Synced passkeys give users the convenience of signing in from any of their devices, at the cost of the credential being backed up to the provider of the sync service; device-bound keys do not sync and are lost with the device.

import { randomBytes } from 'node:crypto';

// Server: issue a registration challenge and remember it per user session.
export function newRegistrationOptions(user: User, rp: RelyingParty) {
  const challenge = randomBytes(32).toString('base64url');
  return {
    challenge,                       // stored server-side, single-use
    rp: { id: rp.id, name: rp.name }, // e.g. id "example.com"
    user: { id: Buffer.from(user.id).toString('base64url'), name: user.email, displayName: user.name },
    pubKeyCredParams: [{ type: 'public-key', alg: -7 }], // ES256
    authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred' },
    timeout: 60_000,
    attestation: 'none',
  };
}

The Registration Ceremony

Registration has two steps. The server issues options including the challenge and relying party id; the browser calls navigator.credentials.create, which prompts the user’s authenticator and returns an attestation response; the server verifies the response and stores the credential. The stored record is the credential id, the public key, the sign count and the transports.

The server’s verification checks that the challenge matches the one it issued, that the origin is the expected one, that the relying party id matches, and that the attestation is well formed. If verification passes, the credential is bound to the account. From then on, the credential id identifies the credential at authentication.

// Browser + server: create the credential, then verify and store it.
const options = await fetch('/webauthn/register/options').then((r) => r.json());
const credential = await navigator.credentials.create({
  publicKey: {
    ...options,
    challenge: base64urlToBytes(options.challenge),
    user: { ...options.user, id: base64urlToBytes(options.user.id) },
  },
});

await fetch('/webauthn/register/verify', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(credential), // id, rawId, response, type
});
// server verifies, then stores credentialId + publicKey + signCount

The Authentication Ceremony

Authentication mirrors registration. The server issues a fresh challenge and the list of credential ids registered for the account; the browser calls navigator.credentials.get; the authenticator signs the challenge; the server looks up the stored public key by credential id and verifies the signature. If it verifies, the user is authenticated.

The sign count should increase with each authentication for authenticators that maintain one. If a stored sign count is greater than the incoming one, the credential may have been cloned, which is a signal to reject and alert. Some authenticators always report zero and cannot provide this check; treat a zero count as “no counter available” rather than a failure.

export async function verifyAuthentication(
  stored: StoredCredential,
  response: AuthenticatorAssertionResponse,
  expectedChallenge: string,
) {
  const ok = await verifySignature({
    publicKey: stored.publicKey,
    signature: response.signature,
    data: concat(response.authenticatorData, sha256(response.clientDataJSON)),
    algorithm: 'ES256',
  });
  const clientData = JSON.parse(Buffer.from(response.clientDataJSON).toString('utf8'));
  if (!ok) throw new Error('bad_signature');
  if (clientData.challenge !== expectedChallenge) throw new Error('challenge_mismatch');
  if (!isExpectedOrigin(clientData.origin)) throw new Error('origin_mismatch');
  return true;
}

What the Server Must Verify

Verify the challenge equality, the origin, the relying party id hash in the authenticator data, and the signature. The origin check is what makes passkeys phishing-resistant: a look-alike domain has a different origin, so the credential created for your site cannot be used to sign in there, and a credential from the phishing site does not verify on yours.

Bind the challenge to the user’s session and invalidate it after one use. A challenge reusable across attempts would reintroduce replay. Also verify the flags: user verification means the authenticator checked the user (biometric or PIN), and the user present flag confirms a human was involved. Require user verification for high-assurance operations.

# server-side verification checklist
[ ] challenge equals the one issued for THIS session, then invalidate it
[ ] clientData.type == "webauthn.get" (auth) / "webauthn.create" (register)
[ ] clientData.origin is exactly your origin (no subdomain surprises)
[ ] rpIdHash matches sha256(your rpId)
[ ] signature verifies over authenticatorData || sha256(clientDataJSON)
[ ] signCount increased (unless authenticator reports 0)
[ ] UV flag set when you require user verification

Storing Credentials and Recovery

Store one row per credential: credential id, public key, sign count, transports, created time and a label. A user may have several passkeys (phone, laptop, security key), so model a one-to-many relationship and let them manage and revoke individual credentials. The public key is not a secret, but the credential id is an identifier and should be indexed for lookup at authentication.

Plan recovery, because a user who loses every device is locked out. Offer a second factor, a backup passkey on another device, recovery codes stored securely, or an administrative recovery flow with identity verification. Recovery is the soft underbelly of any strong scheme; a weak recovery path undermines the passkey’s strength, so make recovery deliberate and auditable.

# credential storage
credentials(credential_id PK, user_id FK, public_key, sign_count,
            transports, created_at, last_used_at, label)
# a user may hold many credentials; allow listing and revocation
# recovery: backup passkey OR one-time recovery codes OR verified admin flow

Common Pitfalls and Conclusion

Do not skip the origin check, which is the whole point of WebAuthn. Do not reuse challenges. Do not store the private key; you never see it. Do not ignore the sign count for authenticators that provide one. Do not build a weak recovery path that bypasses the very protection passkeys provide. And do not assume the browser is available: older environments still need a fallback factor.

WebAuthn replaces shared secrets with signatures over a server challenge, and the origin and challenge checks are what make it phishing-resistant. Issue single-use challenges, verify origin, relying party id and signature, store only the public key with a sign count, and design a deliberate recovery path. Done well, passkeys remove the password from your attack surface without adding friction for the user.

Sources: W3C: Web Authentication (WebAuthn), FIDO Alliance: Passkeys, MDN: PublicKeyCredential.

FAQ

Why are passkeys phishing-resistant?
Because the signature is bound to the origin. A credential created for your domain cannot produce a signature that verifies on a look-alike domain, and a challenge signed on a phishing site does not verify on yours, so there is no passcode to type into a fake page.
What happens if a user loses all their devices?
That is why recovery must be designed explicitly: a backup passkey on another device, one-time recovery codes stored securely, or an identity-verified administrative recovery. A weak recovery path undermines the strength of the passkey, so make it deliberate and auditable.

Related Examples