Interactive Lab

Modern Auth: Passkeys, WebAuthn & Session Security

Implement passwordless WebAuthn authentication, secure HttpOnly session cookie rotation, and evaluate client storage security models.

auth-and-cookies.ts
import { generateRegistrationOptions, verifyRegistrationResponse } from '@simplewebauthn/server';

// 1. Passwordless WebAuthn / Passkey Registration Challenge
export async function createPasskeyChallenge(user: { id: string; email: string }) {
  const options = await generateRegistrationOptions({
    rpName: 'Web Engine 2026',
    rpID: 'localhost',
    userID: new TextEncoder().encode(user.id),
    userName: user.email,
    attestationType: 'none',
    authenticatorSelection: {
      residentKey: 'required',
      userVerification: 'preferred'
    }
  });

  // Store options.challenge securely in server-side session
  return options;
}

// 2. Secure HttpOnly Session Cookie Issuance
export function setSessionCookie(cookies: { set: Function }, sessionId: string) {
  cookies.set('app_session', sessionId, {
    httpOnly: true,     // Immune to JavaScript document.cookie XSS theft
    secure: true,       // HTTPS transmission only
    sameSite: 'lax',    // CSRF protection for top-level navigations
    path: '/',
    maxAge: 60 * 60 * 24 * 7 // 7-day rolling duration
  });
}

Security Principles

  • Passkeys (WebAuthn): Cryptographic public-private keypairs anchored in hardware secure enclaves (TouchID, FaceID, Windows Hello). Immune to phishing and credential stuffing.
  • HttpOnly Session Cookies: Cannot be read via JavaScript (document.cookie), protecting session IDs from XSS exfiltration.
  • CSRF Mitigation: Pairing SameSite: 'lax' cookies with custom authorization headers or anti-forgery tokens prevents cross-site request forgery.
WebAuthn / Passkey Registration Public-Key Cryptography
1. Server Challenge
2. Biometric Sign
3. Key Verified ✓
Client Storage Security Evaluation
HttpOnly Cookie XSS Safe: YES

Best for: Session IDs, Refresh Tokens

localStorage XSS Safe: NO

Best for: Themes, non-sensitive UI state

IndexedDB XSS Safe: NO

Best for: Large offline datasets