Safe WebAuthn/Passkeys Rollout Guide
As Sherlock from Trailblazer Labs, I'll guide you through building a secure, phishing-resistant WebAuthn/passkey rollout . This follows FIDO Alliance best practices, W3C specs, and real-world implementations (e.g., from Google, Apple, Microsoft). Passkeys are phishing-resistant by design because credentials are bound to your domain's Relying Party ID (RP ID) and require user verification (UV).
Key principles:
HTTPS-only : Enforce HSTS.
RP ID : Use your exact domain (e.g., example.com, not www.example.com unless matching).
User control : Always show origin in UI.
No secrets on server : Store only public keys.
Recovery-first : Design for loss upfront.
We'll cover:
Ceremonies (registration/auth).
Phishing resistance .
Recovery .
Implementation (client/server code).
Rollout checklist .
1. Prerequisites
Server : Node.js/Express + @simplewebauthn/server (handles crypto/challenges).
Client : Modern browser (Chrome 109+, Safari 16+, Firefox 122+).
RP ID : Set to your root domain (e.g., example.com).
Origins : https://example.com.
Libraries:
bash Copy code
npm i @simplewebauthn/server @simplewebauthn/browser
2. Ceremonies
Registration Ceremony (Credential Creation)
Server generates challenge → Client creates credential → Server verifies/stores.
UI Flow :
Show: "Create passkey for example.com? [Your Device Name]"
Require user gesture (e.g., button click).
Use userVerification: 'required' for PIN/biometrics.
Server (Node.js) :
js Copy code
const { generateRegistrationOptions, verifyRegistrationResponse } = require('@simplewebauthn/server');
app.post('/auth/register/start', async (req, res) => {
const options = generateRegistrationOptions({
rpName: 'Example App',
rpID: 'example.com', // Phishing protection: exact domain
userID: req.user.id, // Your user UUID
userName: req.user.email,
attestationType: 'none', // Or 'indirect' for privacy
authenticatorSelection: {
userVerification: 'required', // PIN/face/biometrics
residentKey: 'required', // Discoverable credential (no username needed)
requireResidentKey: true
},
timeout: 60000
});
// Store challenge in session/DB (TTL 5min)
req.session.challenge = options.challenge;
res.json(options);
});
app.post('/auth/register/finish', async (req, res) => {
const { credential } = req.body;
const verification = await verifyRegistrationResponse({
response: credential,
expectedChallenge: req.session.challenge,
expectedOrigin: 'https://example.com',
expectedRPID: 'example.com'
});
if (verification.verified) {
// Store: verification.registrationInfo.credentialPublicKey, userID, etc.
await db.users.update(req.user.id, { webauthn: verification.registrationInfo });
res.json({ success: true });
} else {
res.status(400).json({ error: 'Invalid registration' });
}
});
Client (Browser) :
js Copy code
import { startRegistration } from '@simplewebauthn/browser';
async function register() {
const options = await fetch('/auth/register/start').then(r => r.json());
const attestation = await startRegistration(options);
await fetch('/auth/register/finish', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential: attestation })
});
}
Authentication Ceremony (Sign-In)
Server challenge → Client gets/uses credential → Server verifies signature.
UI Flow :
Auto-prompt: "Use passkey? [Device/Passkey Name]"
Fallback: "Other options" (e.g., magic link).
Server :
js Copy code
const { generateAuthenticationOptions, verifyAuthenticationResponse } = require('@simplewebauthn/server');
app.post('/auth/login/start', async (req, res) => {
const user = await db.users.findByEmail(req.body.email); // Or allowAllCredentials=true for hybrid
const options = generateAuthenticationOptions({
rpID: 'example.com',
allowCredentials: user.webauthn ? [{ id: user.webauthn.credentialID, type: 'public-key' }] : [],
userVerification: 'required'
});
req.session.challenge = options.challenge;
res.json(options);
});
app.post('/auth/login/finish', async (req, res) => {
const user = await db.users.findByCredential(req.body.credential.id);
const dbCredential = user.webauthn;
const verification = await verifyAuthenticationResponse({
response: req.body.credential,
expectedChallenge: req.session.challenge,
expectedOrigin: 'https://example.com',
expectedRPID: 'example.com',
credential: dbCredential, // Includes publicKey, counter, etc.
});
if (verification.verified) {
// Update counter, issue session/JWT
await db.users.updateCounter(user.id, verification.verification.counter);
res.json({ token: generateJWT(user.id) });
}
});
Client :
js Copy code
import { startAuthentication } from '@simplewebauthn/browser';
async function login() {
const options = await fetch('/auth/login/start', {
method: 'POST',
body: JSON.stringify({ email: 'user@example.com' })
}).then(r => r.json());
const asse = await startAuthentication(options);
const token = await fetch('/auth/login/finish', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential: asse })
}).then(r => r.json());
}
3. Phishing Resistance
WebAuthn binds credentials to RP ID + Origin :
Client checks : Browser prompts only for exact example.com.
Server enforces : expectedRPID, expectedOrigin in verification.
Best Practices :
Measure Why residentKey: 'required'No phishing via username reuse. userVerification: 'required'Biometrics/PIN blocks remote attacks. Conditional UI mediation: 'conditional' auto-suggests passkeys.HSTS + CAA Prevent downgrade/MitM. Show origin in UI "Signing into example.com". Subdomain isolation Use separate RP IDs (e.g., app.example.com).
Test Phishing : Try on evil.com → Browser blocks.
4. Recovery
Never single-point failure . Require 2+ passkeys at registration.
Mechanisms (Layered)
Multi-Passkey (Primary):
Prompt: "Add 2nd passkey on phone?"
Server: Store array of credentials per user.
UI: List/manage/delete in settings.
Cloud Sync (Seamless):
Apple/Google/MS sync passkeys across devices.
No server involvement.
Backup Codes (Fallback):
Generate 10 one-time TOTP-like codes at signup.
js Copy code
// Server: Use speakeasy or otplib
const backupCodes = speakeasy.generateKey({ length: 10, name: Math.random().toString(36) });
await db.users.update(user.id, { backupCodes: backupCodes.base32 });
Redeem: verify( code ) → Temp session → Re-register passkeys.
Recovery Key (Advanced):
Wrapped symmetric key (e.g., via WebCrypto) for re-encrypting user data.
Or account recovery flow: Email + backup code + new device.
Social Recovery (Optional, Risky):
Guardians (trusted contacts) approve via their passkeys.
Use threshold sigs (e.g., via @tbd54566975/guardian-network).
Recovery Flow :
code Copy code
Lost all? → Enter backup code → Re-register passkeys → Revoke old ones.
Server Revoke :
js Copy code
await db.users.update(user.id, { webauthn: [] }); // Force re-reg
5. Rollout Checklist
Potential Pitfalls
Cross-browser : Firefox needs authenticatorSelection.attachReset: false.
Incognito : No sync → Prompt backup.
Corporate : YubiKeys for hardware.
This is production-ready. Audit with tools like webauthn.io/tester. Questions? Provide your stack for tweaks. 🔒