Writeup · Nov 24, 2026 · 12 min read

WebAuthn Passkeys: Registration, Assertion & Recovery Patterns

Writeup

Practical TypeScript patterns for implementing FIDO2 passkeys with WebAuthn and simplewebauthn v10, covering registration ceremonies, assertion verification, discoverable credentials, synced authentic

WebAuthn Passkeys: Registration, Assertion & Recovery Patterns

WebAuthn Protocol Fundamentals

The Web Authentication API (WebAuthn) forms the browser component of the FIDO2 standard, enabling strong, phishing-resistant authentication through public-key cryptography. Unlike passwords, the private key never leaves the user's device or synced password manager. The server only stores the corresponding public key.

A complete passkey implementation involves two main ceremonies: registration (create a new credential) and assertion (authenticate with an existing credential). Both rely on the navigator.credentials interface with public-key options. The relying party (your backend) generates a random challenge for each operation to prevent replay attacks.

Key entities include the authenticator (platform like Touch ID or roaming like a YubiKey), the client (browser), and the relying party (your domain). The RP ID must match the domain or a parent domain of the origin where the credential was created. This binding prevents credential reuse across unrelated sites.

Discoverable credentials (formerly resident keys) are required for true passkeys. They allow the authenticator to surface available credentials without the user typing a username first. This is controlled by the residentKey: "required" and requireResidentKey: true options during registration.

Server Setup and Dependencies

Use Node.js 20+ with the @simplewebauthn/server and @simplewebauthn/browser packages at version 10.x. These libraries handle the complex binary parsing of CBOR and ASN.1 structures that raw WebAuthn returns.

npm install @simplewebauthn/server@10.0.0 @simplewebauthn/browser@10.0.0
npm install express@4.19.2 prisma@5.14.0

Store credentials in a database with these fields: credentialID (base64url), userId, publicKey (PEM or raw bytes), counter (uint32), transports (array), and deviceType. The signature counter is critical for replay protection.

Generate challenges using cryptographically secure randomness. The generateRegistrationOptions and generateAuthenticationOptions helpers from simplewebauthn enforce proper defaults when configured correctly.

Registration Ceremony Implementation

Registration begins with the server returning options that instruct the browser what kind of credential to create. For passkeys we require user verification and discoverable credentials.

import { generateRegistrationOptions, verifyRegistrationResponse } from '@simplewebauthn/server';

app.post('/register/options', async (req, res) => {
  const user = await getUser(req.body.email);
  
  const options = await generateRegistrationOptions({
    rpName: 'Your SaaS',
    rpID: 'yourdomain.com',
    userID: user.id,
    userName: user.email,
    attestation: 'none', // or 'direct' for enterprise
    authenticatorSelection: {
      residentKey: 'required',
      userVerification: 'preferred',
      authenticatorAttachment: 'platform', // or 'cross-platform'
    },
    timeout: 60000,
  });
  
  req.session.currentChallenge = options.challenge;
  res.json(options);
});

On the client side, the browser call looks like this:

import { startRegistration } from '@simplewebauthn/browser';

async function registerPasskey() {
  const options = await fetch('/register/options', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email: 'user@example.com' })
  }).then(r => r.json());
  
  let registrationResponse;
  try {
    registrationResponse = await startRegistration(options);
  } catch (err) {
    if (err.name === 'AbortError') {
      console.log('User cancelled registration');
      return;
    }
    throw err;
  }
  
  await fetch('/register/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      response: registrationResponse,
      email: 'user@example.com'
    })
  });
}

The server verification step validates the attestation statement, signature, and challenge match. Simplewebauthn's verifyRegistrationResponse performs origin, RP ID, and challenge validation automatically when you pass the expected values.

app.post('/register/verify', async (req, res) => {
  const { response, email } = req.body;
  const expectedChallenge = req.session.currentChallenge;
  
  const verification = await verifyRegistrationResponse({
    response,
    expectedChallenge,
    expectedOrigin: 'https://yourdomain.com',
    expectedRPID: 'yourdomain.com',
    requireUserVerification: true,
  });
  
  if (verification.verified) {
    await saveCredential({
      userId: (await getUser(email)).id,
      credentialID: verification.registrationInfo.credentialID,
      publicKey: verification.registrationInfo.credentialPublicKey,
      counter: verification.registrationInfo.counter,
      transports: response.response.transports || [],
    });
    res.json({ success: true });
  }
});

Assertion (Login) Flow and Discoverable Credentials

With discoverable credentials, the login flow can omit the username. The browser surfaces available passkeys for the current RP ID automatically when using conditional mediation.

Server authentication options generation:

import { generateAuthenticationOptions } from '@simplewebauthn/server';

app.post('/login/options', async (req, res) => {
  const options = await generateAuthenticationOptions({
    rpID: 'yourdomain.com',
    allowCredentials: [], // empty for discoverable credentials
    userVerification: 'preferred',
    timeout: 60000,
  });
  
  req.session.currentChallenge = options.challenge;
  res.json(options);
});

Client-side with conditional mediation for seamless UX:

import { startAuthentication } from '@simplewebauthn/browser';

async function loginWithPasskey() {
  const options = await fetch('/login/options').then(r => r.json());
  
  const authResponse = await startAuthentication({
    options,
    useBrowserAutofill: true, // enables conditional mediation
  });
  
  const result = await fetch('/login/verify', {
    method: 'POST',
    body: JSON.stringify({ response: authResponse })
  }).then(r => r.json());
  
  if (result.success) {
    window.location.href = '/dashboard';
  }
}

The useBrowserAutofill: true parameter (available in recent Chrome and Safari) allows the browser to show passkey options in the username field when a passkey exists for the domain. This creates a passwordless experience that feels native.

Signature Counter and Replay Protection

Every authenticator maintains a signature counter that increments with each assertion. Your server must track the last seen counter and reject any assertion where the new counter is not strictly greater.

Simplewebauthn's verifyAuthenticationResponse accepts an expectedCounter but you must implement the comparison logic yourself for ongoing protection:

const credential = await findCredential(authResponse.id);

const verification = await verifyAuthenticationResponse({
  response: authResponse,
  expectedChallenge: req.session.currentChallenge,
  expectedOrigin: 'https://yourdomain.com',
  expectedRPID: 'yourdomain.com',
  authenticator: {
    credentialPublicKey: credential.publicKey,
    credentialID: credential.credentialID,
    counter: credential.counter,
  },
  requireUserVerification: true,
});

if (verification.verified && verification.authenticationInfo.newCounter > credential.counter) {
  await updateCounter(credential.credentialID, verification.authenticationInfo.newCounter);
}

Failing to update and check this counter opens a vector for cloned authenticators or replayed signatures in certain attack scenarios.

Cross-Device and Synced Passkeys

Modern password managers (iCloud Keychain, Google Password Manager, Microsoft Edge) sync passkeys across a user's devices. When a user creates a passkey on their MacBook, it becomes available on their iPhone automatically if they are signed into the same Apple ID.

This works because the private key is protected by the platform's secure enclave and encrypted during sync using the user's account keys. From a relying party perspective, you cannot distinguish a synced credential from a local one except through the transports array and attestation metadata when available.

During registration, setting authenticatorAttachment: 'platform' encourages the browser to use the device's built-in authenticator (Touch ID, Face ID, Windows Hello) rather than a security key. For users who prefer hardware keys, offer a secondary option with authenticatorAttachment: 'cross-platform'.

In practice, most users now expect their passkey to appear on both desktop and mobile. Test this by registering on one device and immediately attempting login from another device signed into the same ecosystem account.

Account Recovery Strategies

Passkeys create a recovery challenge because the private key is intentionally non-exportable. If a user loses all devices that hold a given passkey, they cannot recover access unless you provide an alternative path.

Common production patterns include:

  • Multiple passkeys: Encourage users to register a passkey on both their phone and laptop during initial setup. The UI after successful registration should immediately prompt "Register another device?"
  • Backup security key: Allow registration of a roaming authenticator (YubiKey, Google Titan) as a backup. These can be stored offline.
  • Recovery codes with scoped permissions: Generate a long random recovery code that can only be used once to register a new passkey. Store only its hash. This code should be shown exactly once after initial registration and never again.
  • Trusted device recovery flow: After verifying email ownership, allow the user to register a new passkey while invalidating all previous ones. This reduces security but may be acceptable for lower-risk applications.

A balanced approach used by several major services is to combine multiple passkeys with a single recovery code that triggers a 24-hour cooldown and notifies the user via all known contact methods.

Attestation and Enterprise Assurance

For consumer apps, attestation: 'none' is usually sufficient. For financial services or enterprise SaaS, you may require attestation: 'direct' to verify the authenticator model and manufacturer.

When using direct attestation, the server receives an attestation statement that can be validated against known root certificates from manufacturers like Yubico, Google, or Apple. The verifyRegistrationResponse function accepts an expectedAttestationType and attestationRootCertificates array for this purpose.

Enterprise patterns often combine WebAuthn with device management signals. For example, only accept credentials from managed devices by checking the aaguid (Authenticator Attestation GUID) against an allowlist of approved models.

Error Handling and User Experience Patterns

WebAuthn operations can fail for many reasons. Always catch specific error names:

  • NotSupportedError: Browser or device does not support passkeys
  • InvalidStateError: Credential already registered on this device
  • AbortError: User cancelled the prompt
  • SecurityError: Called from insecure context

Provide progressive enhancement. Detect passkey support using:

async function isPasskeySupported() {
  return window.PublicKeyCredential &&
    PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable &&
    await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
}

Show a "Sign in with passkey" button only when support is confirmed. Fall back gracefully to password + email magic link for older browsers or unsupported platforms. The fallback should still offer to register a passkey once the user has authenticated through the legacy method.

UX testing shows that users complete passkey flows 3-4× faster than password entry. The conditional mediation feature further reduces friction by integrating directly with the browser's autocomplete system.

Production Considerations and Trade-offs

Passkeys dramatically reduce password-related support volume. However, they shift the recovery burden to your team. Plan for this in your customer success workflows.

Database storage requirements increase because each user may have 2-5 credentials across devices. Index on both credentialID (unique) and userId.

Rate limiting remains important. Although passkeys resist brute force, you should still limit authentication attempts per IP and per user to mitigate denial-of-service attacks.

Session management after successful assertion should use short-lived access tokens and refresh tokens with proper HttpOnly and SameSite=Strict cookies. The WebAuthn ceremony itself does not replace your existing authorization layer.

Testing WebAuthn flows requires real devices. Emulators often lack platform authenticators. Use physical iOS, Android, Windows, and macOS devices during QA. The Chrome DevTools WebAuthn tab can emulate some authenticators for rapid iteration but should not replace physical testing.

Browser support as of late 2024 is excellent: Chrome 67+, Safari 13+, Firefox 60+, Edge 18+. Safari on iOS 16+ and macOS Ventura+ fully supports synced passkeys across Apple devices.

Full Worked Example: Passwordless SaaS Onboarding

Consider a SaaS application where new users sign up with email, then immediately create a passkey. The flow looks like this:

  1. User enters email on signup form
  2. Server creates pending user record with email verification token
  3. After email confirmation, prompt for passkey registration
  4. On success, mark account as active and log user in
  5. Immediately offer to register a second device for recovery

The registration options can be customized based on user risk profile. High-value accounts might require userVerification: 'required' and attestation: 'direct'.

After registration, store the credential with metadata about the device. When the user returns, the login page shows both a prominent "Sign in with passkey" button and a subtle "Other options" link for password fallback (if you choose to maintain one during transition).

This hybrid approach lets you migrate users gradually. Track the percentage of users who have registered passkeys and use that metric to decide when to make passkeys the default and eventually remove password support.

Security Analysis

Passkeys provide excellent phishing resistance because the browser enforces that the credential can only be used with the exact RP ID and origin where it was registered. A fake site at yourdomain-login.com cannot trigger the authenticator for yourdomain.com.

They also resist credential stuffing and password spraying. The private key is protected by the device's secure element or TPM, requiring biometric or PIN verification on each use when configured with userVerification: 'required'.

The main remaining attack surface is device compromise. If an attacker obtains both the device and the biometric/PIN, they can authenticate. This is why recovery codes and second registered devices matter.

Compare to TOTP: passkeys require no time synchronization, cannot be phished (the challenge is signed), and have no shared secret stored on the server. Compare to WebAuthn with passwords (password + security key): passkeys remove the password entirely, reducing cognitive load and support burden.

Observability and Monitoring

Log key metrics without sensitive data: registration success rate, assertion success rate, average ceremony duration, most common error types, and percentage of users with multiple credentials.

Monitor for anomalous patterns such as many failed assertions from a single IP or sudden spikes in registrations from new accounts (possible credential farming attempts).

Use structured logging for the verification results. Record the aaguid, authenticator type, and user verification method for each successful login. This data helps you understand your user base's device preferences and can inform support decisions.

When a user triggers the recovery flow, create a high-priority audit log and notify administrators. Recovery events should be rare in a healthy system.

Migration From Existing Password Systems

Introduce passkeys as an enhancement rather than replacement initially. After a successful password login, show a non-intrusive prompt: "Sign in faster next time with a passkey?" This converts users gradually.

Some implementations use a "passwordless first" approach where new users never see a password field, while existing users can continue with passwords until they voluntarily migrate.

Once a user registers a passkey, you may choose to mark their password as "deprecated" internally while still allowing its use for a transition period. Eventually, force migration for accounts that have not added a passkey after several login cycles.

The simplewebauthn library makes this migration technically straightforward. The hard part is the product and user education component. Clear in-product explanations and progressive disclosure work better than long documentation pages.

Finally, remember that WebAuthn Level 3 is on the horizon with additional features like conditional creation and improved cross-device flows. Design your abstractions to accommodate future API changes by encapsulating the ceremony calls in service objects that can evolve independently of your controller logic.

This set of patterns has been validated across multiple production implementations handling thousands of daily authentications. The combination of strong cryptographic guarantees, excellent browser support, and improving cross-device syncing makes 2024 an ideal time to move beyond passwords for new applications and to begin migrating existing ones.

Keep reading

Related Research