惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
小众软件
小众软件
爱范儿
爱范儿
Y
Y Combinator Blog
博客园 - Franky
美团技术团队
博客园 - 【当耐特】
The Cloudflare Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
IT之家
IT之家
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
WordPress大学
WordPress大学
V
Visual Studio Blog
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Passkeys in 2026: A Practical Engineering Guide to Passwo...
Moksh Gupta · 2026-06-20 · via DEV Community

Authentication is broken at its foundation - not just inconvenient. Passwords are shared secrets: hand one to a server, and you have instantly doubled your attack surface. With over 5 billion passkeys now active globally and Google reporting a 99.9% lower account compromise rate compared to passwords, the industry has already moved. This guide covers how passkeys work cryptographically, how to implement them in TypeScript, and the pitfalls to avoid before going to production.

Why Passwords Are Structurally Broken

The core issue isn't that users pick weak passwords - it's that passwords require a shared secret stored on both sides. The Verizon 2025 DBIR found that 22% of all breaches started with stolen credentials, and 88% of web app attacks relied on them. In 2024, infostealer malware alone harvested 548 million passwords. Adding 2FA helps but doesn't fix the root problem: SMS codes are SIM-swap targets, and TOTP tokens can be phished in real time by proxy attackers who replay codes within their validity window.

What Passkeys Actually Are

A passkey is a credential built on public-key cryptography, standardized through the WebAuthn spec and FIDO2. When you register, your device generates a public-private key pair - the private key stays locked in hardware (Secure Enclave, StrongBox, or a hardware key), and the server only receives the public key. At login, the server sends a random challenge, your device signs it with the private key after biometric or PIN verification, and the server verifies the signature. No secret is ever transmitted. This eliminates credential stuffing, server-side breach exposure, and phishing - because passkeys are cryptographically bound to a specific origin domain.

The Cryptography Worth Understanding

The standard algorithm is ES256 - ECDSA with the P-256 curve and SHA-256. Each credential is tied to a specific relying party ID (your app's domain). A passkey created for yourapp.com cannot be used on yourapp-phishing.com because the origin is embedded in clientDataJSON and verified by the authenticator before it signs anything. The registration flow involves your server generating a one-time challenge, the client calling navigator.credentials.create(), the authenticator signing an attestation with the new private key, and your server verifying and storing the public key and credential ID. Authentication mirrors this with navigator.credentials.get().

Implementing Registration with SimpleWebAuthn

Don't implement raw WebAuthn from scratch - CBOR decoding and signature verification are easy to misconfigure. The standard library for TypeScript/Node.js is SimpleWebAuthn, which handles cryptographic complexity through a clean API and sees 800K+ weekly npm downloads. Install both packages:

npm install @simplewebauthn/server @simplewebauthn/browser

Server side - Registration options endpoint (Express):

import {
  generateRegistrationOptions,
  verifyRegistrationResponse,
} from "@simplewebauthn/server";
import type { RegistrationResponseJSON } from "@simplewebauthn/types";

const rpName = "Your App Name";
const rpID = "yourapp.com";
const origin = `https://${rpID}`;

app.get("/auth/register/options", requireSession, async (req, res) => {
  const user = req.user;
  const options = await generateRegistrationOptions({
    rpName,
    rpID,
    userName: user.email,
    userDisplayName: user.name,
    excludeCredentials: user.passkeys.map((pk) => ({
      id: pk.credentialID,
      transports: pk.transports,
    })),
    authenticatorSelection: {
      residentKey: "required",
      userVerification: "required",
    },
  });
  req.session.registrationChallenge = options.challenge;
  res.json(options);
});

app.post("/auth/register/verify", requireSession, async (req, res) => {
  const body: RegistrationResponseJSON = req.body;
  const expectedChallenge = req.session.registrationChallenge;

  let verification;
  try {
    verification = await verifyRegistrationResponse({
      response: body,
      expectedChallenge,
      expectedOrigin: origin,
      expectedRPID: rpID,
    });
  } catch (error) {
    return res.status(400).json({ error: (error as Error).message });
  }

  const { verified, registrationInfo } = verification;
  if (verified && registrationInfo) {
    const { credential, credentialDeviceType, credentialBackedUp } =
      registrationInfo;
    await db.passkeys.create({
      userId: req.user.id,
      credentialID: credential.id,
      credentialPublicKey: Buffer.from(credential.publicKey),
      counter: credential.counter,
      deviceType: credentialDeviceType,
      backedUp: credentialBackedUp,
      transports: body.response.transports ?? [],
    });
    req.session.registrationChallenge = undefined;
  }
  res.json({ verified });
});

Client side - Registration:

import {
  startRegistration,
  browserSupportsWebAuthn,
} from "@simplewebauthn/browser";

async function registerPasskey() {
  if (!browserSupportsWebAuthn()) {
    alert("Your browser does not support passkeys.");
    return;
  }

  const optionsRes = await fetch("/auth/register/options");
  const options = await optionsRes.json();

  let attResp;
  try {
    attResp = await startRegistration({ optionsJSON: options });
  } catch (error) {
    if ((error as Error).name === "InvalidStateError") {
      console.error("This device already has a passkey registered.");
    } else {
      console.error(error);
    }
    return;
  }

  const verifyRes = await fetch("/auth/register/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(attResp),
  });
  const result = await verifyRes.json();
  if (result.verified) {
    console.log("Passkey registered successfully!");
  }
}

Implementing Authentication

The login flow mirrors registration - generate a challenge, have the authenticator sign it, and verify server-side. Registration and login together clock in at roughly 150 lines using SimpleWebAuthn.

Server side - Authentication:

import {
  generateAuthenticationOptions,
  verifyAuthenticationResponse,
} from "@simplewebauthn/server";
import type { AuthenticationResponseJSON } from "@simplewebauthn/types";

app.get("/auth/login/options", async (req, res) => {
  const options = await generateAuthenticationOptions({
    rpID,
    userVerification: "required",
  });
  req.session.authChallenge = options.challenge;
  res.json(options);
});

app.post("/auth/login/verify", async (req, res) => {
  const body: AuthenticationResponseJSON = req.body;
  const expectedChallenge = req.session.authChallenge;

  const passkey = await db.passkeys.findByCredentialID(body.id);
  if (!passkey) {
    return res.status(400).json({ error: "Unknown credential" });
  }

  let verification;
  try {
    verification = await verifyAuthenticationResponse({
      response: body,
      expectedChallenge,
      expectedOrigin: origin,
      expectedRPID: rpID,
      credential: {
        id: passkey.credentialID,
        publicKey: new Uint8Array(passkey.credentialPublicKey),
        counter: passkey.counter,
        transports: passkey.transports,
      },
    });
  } catch (error) {
    return res.status(400).json({ error: (error as Error).message });
  }

  const { verified, authenticationInfo } = verification;
  if (verified) {
    await db.passkeys.updateCounter(
      passkey.credentialID,
      authenticationInfo.newCounter
    );
    const user = await db.users.findById(passkey.userId);
    req.session.userId = user.id;
    req.session.authChallenge = undefined;
  }
  res.json({ verified });
});

Client side - Authentication:

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

async function signInWithPasskey() {
  const optionsRes = await fetch("/auth/login/options");
  const options = await optionsRes.json();

  let assnResp;
  try {
    assnResp = await startAuthentication({ optionsJSON: options });
  } catch (error) {
    console.error("Authentication failed:", error);
    return;
  }

  const verifyRes = await fetch("/auth/login/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(assnResp),
  });
  const result = await verifyRes.json();
  if (result.verified) {
    window.location.href = "/dashboard";
  }
}

Where Adoption Stands Right Now

FIDO Alliance research from April 2026 across 11,000 consumers in 10 countries shows 75% of people globally have at least one passkey enabled, up from 69% just six months prior. Awareness hit 90%, up from 39% two years ago. Google serves 800 million passkey-enabled accounts with sign-in success rates 4x higher than passwords. Amazon has 175 million passkey users, and TikTok reports a 97% auth success rate. A February 2026 arXiv study found 11.3% of the Tranco top-100K websites now support passkeys - 62 times more than manual directory audits suggested. If your app doesn't support passkeys yet, you're behind the median curve.

Four Common Implementation Bugs

These show up repeatedly in developer forums and production incidents.

Challenge reuse - Challenges must be single-use, server-generated, and stored in the session between options generation and verification. Any deviation opens a replay attack window.

Skipping counter updates - The authenticator increments a counter on every auth operation. Comparing incoming vs. stored counters lets you detect cloned credentials. Always call updateCounter after a successful login.

No account recovery path - A user who loses their device loses their passkey. Shipping passkeys without a recovery mechanism - backup email codes, support-verified identity, or recovery keys - means locking users out permanently. Build this before launching.

Cross-device UX dropoff - Same-device passkey completion rates run 79-98%. Cross-device flows on Windows web (QR code + Bluetooth) drop to 52-67%. Keep a password fallback during migration and watch your device mix in analytics.

Migrating From Passwords Without Breaking Things

Treat the migration as three additive stages, not a hard cutover.

Stage 1 - Opt-in: Prompt users to register a passkey after a successful password login. Nothing changes for those who skip it.

Stage 2 - Flip the default: Once 60-70% of active users have passkeys, make the passkey flow primary with password as a secondary option. Conversion follows naturally because the UX is better.

Stage 3 - Require for new signups: New accounts register a passkey as part of onboarding. Apple's OS 26 includes Automatic Passkey Upgrade, which silently creates a passkey on every eligible password sign-in - a useful reference for aggressive migration strategies.

Note for regulated environments: NIST guidelines updated in 2025 require phishing-resistant MFA (explicitly citing WebAuthn/FIDO2) for all US federal agency systems. Syncable passkeys satisfy AAL2.

Browser and Platform Support

WebAuthn has approximately 95% global browser coverage in 2026. Chrome (v67+), Edge (v18+), Safari (v13+ and iOS v14.5+), and all major Chromium forks support it. Platform authenticators cover every major consumer OS: Touch ID and Face ID on Apple devices, Windows Hello on Windows, and Android biometrics on Android 9+. Hardware keys like YubiKey and Google Titan work via USB or NFC for high-assurance enterprise scenarios. Use browserSupportsWebAuthn() from SimpleWebAuthn to gate the passkey UI at runtime.

References