WebAuthn Protocol Fundamentals
The WebAuthn API enables strong, phishing-resistant authentication by using public-key cryptography where private keys remain securely stored on user devices such as laptops, phones, or security keys. The relying party (your server) only stores the corresponding public key. During registration, the authenticator creates a key pair bound to your origin. During authentication, the authenticator signs a server-provided challenge with the private key, and the server verifies the signature using the stored public key.
This mechanism eliminates shared secrets. The protocol defines two main ceremonies: registration (create credential) and authentication (get assertion). WebAuthn Level 2 is the current baseline supported across Chrome 67+, Safari 13+, Firefox 60+, and Edge 18+. Level 3 adds features such as conditional mediation and improved cross-device authentication but remains in working draft status as of late 2024.
Authenticators fall into two categories: platform authenticators (Touch ID, Windows Hello, Android biometric) and roaming authenticators (YubiKey, Titan Security Key). Passkeys specifically leverage discoverable credentials (resident keys) that allow users to sign in without entering a username first. The authenticatorSelection options control these behaviors.
RP ID matching is critical. The RP ID must be an eTLD+1 of the origin. For https://app.example.com, the RP ID is example.com. Mismatches cause silent failures in navigator.credentials.create() and get().
Tools, Versions, and Project Setup
Use Node.js 20 or 22 for the backend. The @simplewebauthn libraries provide type-safe abstractions over the low-level WebAuthn data structures. Install the following packages:
npm install @simplewebauthn/server@10.0.0 @simplewebauthn/browser@10.0.0
npm install express@4.18.2 prisma@5.5.2
On the frontend, target modern browsers with TypeScript 5.2+. For local development, run a HTTPS server because WebAuthn requires secure contexts. Use mkcert or Caddy to generate local certificates. The example codebase uses Express for the API and Prisma for the database layer.
Configure your package.json scripts to include both frontend and backend builds. Ensure your Content Security Policy allows 'self' for script and connect sources. Test on real hardware early—emulators sometimes produce different attestation formats.
Server-Side Registration Challenge Generation
The server must generate cryptographically secure options that the browser consumes. The generateRegistrationOptions function from @simplewebauthn/server handles this.
import { generateRegistrationOptions } from '@simplewebauthn/server';
async function getRegistrationOptions(user) {
const options = await generateRegistrationOptions({
rpName: 'Ajendra Platform',
rpID: 'ajendra.dev',
userID: Buffer.from(user.id),
userName: user.email,
userDisplayName: user.name,
attestation: 'none', // or 'direct' for enterprise
authenticatorSelection: {
authenticatorAttachment: 'platform', // passkey experience
userVerification: 'preferred',
residentKey: 'required', // discoverable credential
requireResidentKey: true
},
supportedAlgorithmIDs: [-7, -257] // ES256, RS256
});
// Store challenge temporarily (Redis or DB) with 10-minute expiry
await saveChallenge(user.id, options.challenge);
return options;
}
The residentKey: 'required' flag creates a discoverable credential suitable for passkeys. userVerification: 'preferred' requests biometric or PIN but falls back gracefully. The challenge must be stored server-side for later verification to prevent replay attacks. Use a Redis instance with a 600-second TTL for production scale.
Frontend Registration Flow with navigator.credentials.create
The browser code transforms the server options into an ArrayBuffer challenge and calls the credentials API. Error handling for NotAllowedError and InvalidStateError is mandatory.
async function registerPasskey() {
const optionsResponse = await fetch('/auth/register/options', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: userEmail })
});
const options = await optionsResponse.json();
// Convert base64 challenge to Uint8Array
options.challenge = base64ToUint8Array(options.challenge);
options.user.id = base64ToUint8Array(options.user.id);
const credential = await navigator.credentials.create({
publicKey: options
});
const registrationData = {
id: credential.id,
rawId: arrayBufferToBase64(credential.rawId),
response: {
attestationObject: arrayBufferToBase64(credential.response.attestationObject),
clientDataJSON: arrayBufferToBase64(credential.response.clientDataJSON)
},
type: credential.type
};
await fetch('/auth/register/verify', {
method: 'POST',
body: JSON.stringify({ registrationData, email: userEmail })
});
}
Helper functions base64ToUint8Array and arrayBufferToBase64 use the TextEncoder and Uint8Array APIs. The clientDataJSON contains origin, challenge, and token binding information that the server validates strictly.
Verifying Registration on the Server
Verification prevents malicious credential injection. Use verifyRegistrationResponse and enforce origin and RP ID checks.
import { verifyRegistrationResponse } from '@simplewebauthn/server';
async function verifyRegistration(registrationData, expectedChallenge, user) {
const verification = await verifyRegistrationResponse({
response: registrationData,
expectedChallenge,
expectedOrigin: 'https://ajendra.dev',
expectedRPID: 'ajendra.dev',
requireUserVerification: true
});
if (!verification.verified) throw new Error('Registration failed');
await prisma.credential.create({
data: {
userId: user.id,
credentialId: verification.registrationInfo.credentialID,
publicKey: Buffer.from(verification.registrationInfo.credentialPublicKey),
counter: verification.registrationInfo.counter,
deviceType: verification.registrationInfo.credentialDeviceType,
backedUp: verification.registrationInfo.credentialBackedUp
}
});
return { success: true };
}
The library returns important metadata including whether the credential is backup eligible. Store the credentialPublicKey as binary. The counter prevents replay attacks on subsequent authentications.
Database Schema for Credential Storage
A normalized schema prevents duplication and supports multiple credentials per user. Using Prisma schema:
model User {
id String @id @default(cuid())
email String @unique
name String
credentials Credential[]
}
model Credential {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id])
credentialId Bytes @unique
publicKey Bytes
counter Int
deviceType String
backedUp Boolean
createdAt DateTime @default(now())
}
Index the credentialId field for fast lookup during authentication. Never store the private key. The backedUp flag indicates whether the passkey was synced to iCloud Keychain or Google Password Manager, informing recovery strategy.
Authentication Challenge Generation
Authentication options can omit the user ID when using discoverable credentials, allowing the browser to show an account selector.
async function getAuthenticationOptions() {
return await generateAuthenticationOptions({
rpID: 'ajendra.dev',
allowCredentials: [], // empty for discoverable credentials
userVerification: 'preferred',
timeout: 60000
});
}
For non-discoverable flows (security keys), populate allowCredentials with previously registered credential IDs. The timeout value of 60 seconds balances security and user patience. Log authentication attempts for rate limiting—implement a 5 attempts per 5 minutes policy per IP and per user.
Browser Authentication Flow
The authentication call mirrors registration but uses navigator.credentials.get().
async function authenticateWithPasskey() {
const optionsResponse = await fetch('/auth/login/options');
let options = await optionsResponse.json();
options.challenge = base64ToUint8Array(options.challenge);
if (options.allowCredentials) {
options.allowCredentials = options.allowCredentials.map(cred => ({
...cred,
id: base64ToUint8Array(cred.id)
}));
}
const assertion = await navigator.credentials.get({
publicKey: options
});
const assertionData = {
id: assertion.id,
rawId: arrayBufferToBase64(assertion.rawId),
response: {
authenticatorData: arrayBufferToBase64(assertion.response.authenticatorData),
clientDataJSON: arrayBufferToBase64(assertion.response.clientDataJSON),
signature: arrayBufferToBase64(assertion.response.signature),
userHandle: assertion.response.userHandle ?
arrayBufferToBase64(assertion.response.userHandle) : null
},
type: assertion.type
};
const result = await fetch('/auth/login/verify', {
method: 'POST',
body: JSON.stringify({ assertionData })
});
return result.ok;
}
Conditional mediation (mediation: 'conditional' in the get options) enables the browser to show passkey suggestions automatically in login forms. This feature is available in Chrome 118+ and Safari 16.6+.
Server Verification of Authentication Assertions
Verification must update the signature counter and check for monotonic increase to prevent cloning attacks.
async function verifyAuthentication(assertionData, user) {
const credential = await prisma.credential.findUnique({
where: { credentialId: Buffer.from(base64ToUint8Array(assertionData.id)) }
});
if (!credential) throw new Error('Credential not found');
const verification = await verifyAuthenticationResponse({
response: assertionData,
expectedChallenge: storedChallenge,
expectedOrigin: 'https://ajendra.dev',
expectedRPID: 'ajendra.dev',
authenticator: {
credentialPublicKey: credential.publicKey,
credentialID: credential.credentialId,
counter: credential.counter
},
requireUserVerification: true
});
if (verification.verified) {
await prisma.credential.update({
where: { id: credential.id },
data: { counter: verification.authenticationInfo.newCounter }
});
return createSession(user);
}
}
The counter check is performed automatically by the library when you pass the stored value. Always require user verification for high-security applications. Log the userVerified boolean from the verification result.
Supporting Multiple Passkeys per User Account
Users often register both a laptop and a phone. Query all credentials belonging to a user during non-discoverable authentication flows. Provide a management UI that lists registered devices with their creation date, last used timestamp, and backup status.
When a user registers a new passkey, check for existing credentials with the same credentialId to prevent duplicates. Offer a "Sign in with another device" fallback that uses QR code based cross-device authentication (caBLE) when the primary device is unavailable. The WebAuthn Level 3 specification improves this flow with better transport hints.
Recovery Mechanisms and Account Access Restoration
Passkeys introduce new failure modes. If a user loses all registered devices, account recovery becomes challenging because there is no shared secret to reset. Implement backup codes (12-16 random words) generated at registration time and stored hashed in the database. Require users to print or store these codes securely.
Alternative recovery paths include email magic links with short expiration (15 minutes) combined with additional signals such as device fingerprinting or knowledge-based questions for high-value accounts. Some platforms use social recovery by allowing designated trusted contacts to approve recovery requests after a cooldown period.
Track credential backup status returned by the library. If all credentials report backedUp: false, prompt the user to add a second device immediately. Provide clear UI copy explaining that passkeys are tied to specific devices or cloud sync services.
Security Properties and Threat Model
Passkeys provide strong phishing resistance because the private key is bound to the RP ID and origin. A fake site at ajendra-login.com cannot obtain a signature valid for ajendra.dev. Token binding further mitigates man-in-the-middle attacks when supported by the client and server.
Attestation can be used in enterprise environments to verify the make and model of the authenticator. For consumer apps, attestation: 'none' preserves privacy. The threat of physical device compromise remains; however, biometric sensors typically use secure enclaves (Secure Enclave on Apple, Titan M2 on Pixel) that prevent key extraction even if the OS is compromised.
Implement rate limiting on authentication endpoints (max 10 attempts per hour per IP). Monitor for anomalous patterns such as sudden spikes in failed signature verifications that might indicate brute-force attempts against the public keys (though computationally infeasible for ECDSA P-256).
Browser Support Matrix and Progressive Enhancement
As of October 2024, passkey support is available in:
- Chrome/Edge 108+ on Windows, macOS, Android, ChromeOS
- Safari 16.6+ on macOS Ventura and iOS 16.6+
- Firefox 119+ with limited platform authenticator support
Provide password fallback for older browsers and enterprise environments that disable platform authenticators. Detect support using feature detection:
const supportsPasskeys = async () => {
if (!window.PublicKeyCredential) return false;
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
};
When support is absent, fall back to email + password + WebAuthn security keys. Use progressive enhancement so the login form shows the "Sign in with passkey" button only after confirming availability.
Performance, UX Tradeoffs and Production Considerations
Passkey authentication typically completes faster than password + TOTP flows because it eliminates typing and context switching to an authenticator app. The cryptographic operations take less than 300ms on modern hardware. However, first-time registration requires user education.
Measure completion rates in your analytics. A/B test button placement and copy ("Sign in with passkey" vs "Use saved credential"). Provide inline explanations or tooltips explaining the benefits. For mobile web, ensure the site is added to the home screen for optimal platform authenticator experience.
In production, deploy the verification logic behind an API gateway with request signing. Use short-lived challenges (maximum 5 minutes) to reduce replay windows. Store challenges in Redis rather than the primary database for lower latency. Implement observability by logging verification success/failure rates, average authentication time, and credential type distribution without recording personally identifiable challenge data.
Consider managed services such as Passkey providers from Apple, Google, Microsoft, or third-party identity platforms (Auth0, Clerk, Stytch) if you prefer to outsource the complexity. Self-implementation gives full control over UX and data residency but requires ongoing maintenance as the WebAuthn specification evolves.
Integration Patterns with Existing Authentication Systems
Hybrid systems are common. After successful passkey authentication, issue the same JWT or session cookie used for traditional logins. Store the authentication method in the session to enable conditional UI later. For OAuth/OIDC flows, WebAuthn can be used as a step-up authentication method for sensitive operations.
When migrating existing users, offer an in-app prompt to "Create a passkey" after they log in with their password. This gradually reduces password reliance. Never force immediate migration—always provide an escape hatch.
For multi-tenant SaaS applications, scope the RP ID per customer subdomain when possible, or use a single RP ID and include tenant context in the user.id field. Ensure credential IDs remain unique across tenants by combining tenant prefix with a random suffix in the database lookup logic.
Testing WebAuthn Implementations
Automated testing is challenging because browser APIs cannot be easily mocked for end-to-end flows. Use Playwright with real Chromium instances and virtual authenticators. The WebAuthn API in Chrome DevTools supports virtual authenticators via the webauthn command in the CDP.
Example Playwright helper to add a virtual authenticator:
await context.addInitScript(() => {
// Virtual authenticator injection code
});
Unit test the server verification logic by generating test vectors from the FIDO conformance test suite. Maintain a library of known-good and deliberately malformed registration and assertion objects to validate error handling. Run tests against multiple browser versions in CI using BrowserStack or similar services.
Future Directions and Level 3 Features
WebAuthn Level 3 introduces PRF (Pseudo-Random Function) extension for deriving cryptographic material from credentials, enabling new use cases such as encrypted backups. The largeBlob extension allows storing small amounts of encrypted data directly with the credential on supported authenticators.
Cross-device authentication (caBLE v2) is improving, allowing a phone to act as an authenticator for a desktop without QR code friction in some flows. Monitor the FIDO Alliance specifications and browser release notes. The @simplewebauthn library typically adds support for new extensions within one or two minor releases.
Adopting passkeys now positions applications to benefit from these improvements with minimal code changes. The core registration and verification patterns presented here remain stable even as new extensions are added.
By implementing these patterns carefully—paying special attention to challenge storage, origin validation, counter management, and user recovery paths—developers can deliver a modern, secure, and delightful authentication experience that reduces password-related support burden and significantly raises the bar against phishing attacks.
