webauthn
安装方式
先用 Prompt 核对来源与依赖。也可下载安装包。
用 AI 助手安装
复制提示词,让助手先核对固定版本和依赖。
查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "webauthn":https://skillpi.com/zh/skills/deepskill-5fbb57f7ef7c9db9fd3338e395604d2e50ccbd0e97eff9d684e8faa7598b23e7。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。
来源与配置
github.com
配置方式待核实
请查看原始来源中的适用工具、依赖和权限要求。
安装实测待补充
实现基于 WebAuthn 和通行密钥(Passkeys)的无密码认证。适用于添加通行密钥或生物识别登录、实现 FIDO2 认证、替代基于密码的登录方式,并在 Web 应用中构建 Touch ID / Face ID 认证流程。涵盖浏览器端 API、服务器端验证以及 simplewebauthn 库的使用。
介绍来源: third_party · TerminalSkills · 1.0.0 参考来源
SkillPi 解读
- 实测状态
- 未测试
文件浏览
Frontmatter
name: webauthn
description: >-
Implement passwordless authentication with WebAuthn and Passkeys. Use when:
adding passkey/biometric login, implementing FIDO2 authentication, replacing
password-based login, building touch ID / face ID authentication flows in
web apps. Covers browser API, server verification, and simplewebauthn library.
license: Apache-2.0
compatibility: "Requires Node.js 18+, modern browser with WebAuthn support"
metadata:
author: terminal-skills
version: "1.0.0"
category: development
tags: ["webauthn", "passkeys", "authentication", "passwordless", "fido2"]
use-cases:
- "Add passkey registration and login to an Express/Node.js app"
- "Replace password forms with biometric authentication"
- "Implement FIDO2 authentication with simplewebauthn"
- "Add Touch ID / Face ID login to a web app"
- "Build a passwordless authentication system from scratch"
agents: [claude-code, openai-codex, gemini-cli, cursor]WebAuthn / Passkeys
Overview
WebAuthn (Web Authentication) lets users authenticate with biometrics (Face ID, Touch ID, Windows Hello) or hardware keys (YubiKey) instead of passwords. Passkeys are WebAuthn credentials synced across devices via iCloud Keychain, Google Password Manager, or 1Password.
Key concepts:
- Relying Party (RP): Your server — verifies credentials
- Authenticator: Device/platform (Touch ID, Face ID, YubiKey)
- Credential: Public/private key pair — private key never leaves device
- Challenge: Server-issued random bytes — prevents replay attacks
Setup
Install @simplewebauthn
npm install @simplewebauthn/server @simplewebauthn/browser
# Types
npm install -D @types/node
SimpleWebAuthn abstracts the low-level CBOR/COSE encoding and handles most edge cases.
Configure Relying Party
// config/webauthn.ts
export const RP_NAME = "My App";
export const RP_ID = process.env.RP_ID || "localhost"; // domain, no protocol/port
export const ORIGIN = process.env.ORIGIN || "http://localhost:3000";
// RP_ID must match the domain of ORIGIN
// For production: RP_ID = "myapp.com", ORIGIN = "https://myapp.com"
Registration Flow
Overview
Client Server
| |
|-- POST /auth/register/begin -->|
| | 1. Generate challenge
|<-- { options } ---------------|
| |
| 2. navigator.credentials.create(options)
| (user taps Touch ID / Face ID)
| |
|-- POST /auth/register/finish ->|
| { credential } | 3. Verify & store public key
|<-- { ok: true } --------------|
Server: generate registration options
// routes/auth.ts
import {
generateRegistrationOptions,
verifyRegistrationResponse,
} from "@simplewebauthn/server";
import { RP_ID, RP_NAME, ORIGIN } from "../config/webauthn";
// In-memory store for demo; use DB in production
const challenges = new Map<string, string>(); // userId → challenge
const credentials = new Map<string, any[]>(); // userId → credentials[]
app.post("/auth/register/begin", async (req, res) => {
const { userId, username } = req.body;
// Fetch existing credentials for the user (to exclude re-registration)
const userCredentials = credentials.get(userId) || [];
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID: RP_ID,
userName: username,
userDisplayName: username,
// Prevent registering the same authenticator twice
excludeCredentials: userCredentials.map((cred) => ({
id: cred.id,
type: "public-key",
})),
authenticatorSelection: {
// "platform" = built-in (Touch ID); "cross-platform" = security key
authenticatorAttachment: "platform",
residentKey: "preferred",
userVerification: "preferred",
},
});
// Store challenge for verification
challenges.set(userId, options.challenge);
res.json(options);
});
Server: verify registration
app.post("/auth/register/finish", async (req, res) => {
const { userId, credential } = req.body;
const expectedChallenge = challenges.get(userId);
if (!expectedChallenge) {
return res.status(400).json({ error: "No challenge found" });
}
let verification;
try {
verification = await verifyRegistrationResponse({
response: credential,
expectedChallenge,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
});
} catch (err) {
return res.status(400).json({ error: (err as Error).message });
}
if (!verification.verified || !verification.registrationInfo) {
return res.status(400).json({ error: "Verification failed" });
}
// Store the credential (save to DB in production)
const { credential: cred } = verification.registrationInfo;
const userCreds = credentials.get(userId) || [];
userCreds.push({
id: cred.id,
publicKey: cred.publicKey,
counter: cred.counter,
deviceType: verification.registrationInfo.credentialDeviceType,
backedUp: verification.registrationInfo.credentialBackedUp,
});
credentials.set(userId, userCreds);
challenges.delete(userId);
res.json({ ok: true });
});
Client: register passkey
// client/auth.ts
import {
startRegistration,
browserSupportsWebAuthn,
} from "@simplewebauthn/browser";
export async function registerPasskey(userId: string, username: string) {
if (!browserSupportsWebAuthn()) {
throw new Error("WebAuthn not supported in this browser");
}
// 1. Get options from server
const optionsRes = await fetch("/auth/register/begin", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, username }),
});
const options = await optionsRes.json();
// 2. Prompt user (opens Touch ID / Face ID)
let credential;
try {
credential = await startRegistration({ optionsJSON: options });
} catch (err: any) {
if (err.name === "InvalidStateError") {
throw new Error("This authenticator is already registered");
}
throw err;
}
// 3. Verify with server
const verifyRes = await fetch("/auth/register/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, credential }),
});
const result = await verifyRes.json();
if (!result.ok) throw new Error(result.error);
return result;
}
Authentication Flow
Overview
Client Server
| |
|-- POST /auth/login/begin ----->|
| | 1. Generate challenge
|<-- { options } ---------------|
| |
| 2. navigator.credentials.get(options)
| (user taps Touch ID)
| |
|-- POST /auth/login/finish ---->|
| { assertion } | 3. Verify signature + counter
|<-- { token } -----------------|
Server: generate authentication options
import {
generateAuthenticationOptions,
verifyAuthenticationResponse,
} from "@simplewebauthn/server";
app.post("/auth/login/begin", async (req, res) => {
const { userId } = req.body;
const userCredentials = credentials.get(userId) || [];
if (userCredentials.length === 0) {
return res.status(400).json({ error: "No passkeys registered" });
}
const options = await generateAuthenticationOptions({
rpID: RP_ID,
allowCredentials: userCredentials.map((cred) => ({
id: cred.id,
type: "public-key",
})),
userVerification: "preferred",
});
challenges.set(userId, options.challenge);
res.json(options);
});
Server: verify authentication
app.post("/auth/login/finish", async (req, res) => {
const { userId, assertion } = req.body;
const expectedChallenge = challenges.get(userId);
const userCredentials = credentials.get(userId) || [];
const credential = userCredentials.find((c) => c.id === assertion.id);
if (!credential) {
return res.status(400).json({ error: "Credential not found" });
}
let verification;
try {
verification = await verifyAuthenticationResponse({
response: assertion,
expectedChallenge: expectedChallenge!,
expectedOrigin: ORIGIN,
expectedRPID: RP_ID,
credential: {
id: credential.id,
publicKey: credential.publicKey,
counter: credential.counter,
},
});
} catch (err) {
return res.status(400).json({ error: (err as Error).message });
}
if (!verification.verified) {
return res.status(401).json({ error: "Authentication failed" });
}
// Update counter (replay attack protection)
credential.counter = verification.authenticationInfo.newCounter;
challenges.delete(userId);
// Issue session/JWT here
const token = issueJWT(userId);
res.json({ ok: true, token });
});
Client: authenticate with passkey
import { startAuthentication } from "@simplewebauthn/browser";
export async function loginWithPasskey(userId: string) {
// 1. Get challenge from server
const optionsRes = await fetch("/auth/login/begin", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId }),
});
const options = await optionsRes.json();
// 2. Prompt user biometric
let assertion;
try {
assertion = await startAuthentication({ optionsJSON: options });
} catch (err: any) {
if (err.name === "NotAllowedError") {
throw new Error("Authentication cancelled or timed out");
}
throw err;
}
// 3. Verify with server
const verifyRes = await fetch("/auth/login/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, assertion }),
});
return verifyRes.json();
}
Database Schema (Production)
-- Users table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Passkeys / credentials
CREATE TABLE passkeys (
id TEXT PRIMARY KEY, -- credential id (base64url)
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
public_key BYTEA NOT NULL, -- stored as bytes
counter BIGINT NOT NULL DEFAULT 0,
device_type TEXT, -- 'platform' | 'cross-platform'
backed_up BOOLEAN DEFAULT FALSE, -- synced passkey?
created_at TIMESTAMPTZ DEFAULT NOW(),
last_used_at TIMESTAMPTZ
);
-- Challenges (short-lived, use Redis TTL in production)
CREATE TABLE challenges (
user_id UUID PRIMARY KEY,
challenge TEXT NOT NULL,
expires_at TIMESTAMPTZ DEFAULT (NOW() + INTERVAL '5 minutes')
);
UI Pattern: Passkey Button
// components/PasskeyButton.tsx
import { registerPasskey, loginWithPasskey } from "@/lib/auth";
import { browserSupportsWebAuthn } from "@simplewebauthn/browser";
export function PasskeyButton({ userId, username, mode }: {
userId: string;
username: string;
mode: "register" | "login";
}) {
if (!browserSupportsWebAuthn()) return null;
const handleClick = async () => {
try {
if (mode === "register") {
await registerPasskey(userId, username);
alert("Passkey registered!");
} else {
const { token } = await loginWithPasskey(userId);
localStorage.setItem("token", token);
}
} catch (err: any) {
alert(err.message);
}
};
return (
<button
onClick={handleClick}
className="flex items-center gap-2 rounded-lg border px-4 py-2"
>
🔑 {mode === "register" ? "Register Passkey" : "Sign in with Passkey"}
</button>
);
}
Other Languages
Python (py_webauthn)
pip install py_webauthn
import webauthn
# Registration
options = webauthn.generate_registration_options(
rp_id="myapp.com",
rp_name="My App",
user_name="alice@example.com",
)
# Verification
verification = webauthn.verify_registration_response(
credential=response,
expected_challenge=challenge,
expected_rp_id="myapp.com",
expected_origin="https://myapp.com",
)
Java (webauthn4j)
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-core</artifactId>
<version>0.22.0</version>
</dependency>
Security Checklist
- [ ] HTTPS required — WebAuthn only works on secure origins (or localhost)
- [ ] RP_ID matches domain — must equal the effective domain, not a subdomain or port
- [ ] Store counter — increment on each auth; reject if counter doesn't increase (replay protection)
- [ ] Short-lived challenges — expire after 5 minutes; delete after use
- [ ] User verification — use
"preferred"or"required"(not"discouraged") - [ ] Exclude existing credentials — pass
excludeCredentialsduring registration - [ ] Backup public key — you can't recover a passkey credential if DB is lost
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
InvalidStateError |
Credential already registered | Pass excludeCredentials in options |
NotAllowedError |
User cancelled or no matching credential | Show friendly error message |
SecurityError |
RP_ID doesn't match origin | Set RP_ID to effective domain |
AbortError |
Operation timed out | Implement retry UI |
| Counter mismatch | Possible cloned authenticator | Log and investigate; block if needed |
当前收录版本
1.0.0
安全与评测信息
质量评测
满分100 · 来自 SkillPi LAB 实验室的评测报告。
亮点
- 提供完整的 WebAuthn/Passkeys 无密码认证端到端实现
- 涵盖注册、登录、数据库设计、UI 组件及多语言支持
- 解决现代 Web 应用安全登录的高频刚需痛点
亮点
- 触发描述完整覆盖多种使用场景(通行密钥、FIDO2、生物识别等)
- 边界清晰,变体覆盖充分,无歧义
亮点
- 文档结构清晰,分章节详述各流程
- 每部分均有详细代码示例和步骤说明
- frontmatter 完整,包含兼容性、标签、用例等信息
亮点
- 使用官方推荐的 @simplewebauthn 库,参数配置正确
- 涵盖主要异常处理(InvalidStateError、NotAllowedError 等)
- 挑战值短期存储,计数器更新防重放攻击
取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。
正文静态检测
100 / 100 · skillpi-20261123-no-r3-v1
正文未命中当前规则。
分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。
权限与使用前检查
根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。
-
安装或获取外部依赖
使用官方来源并锁定版本,在隔离环境检查安装脚本。当前文档检查不覆盖后续下载的代码。
主文档提及 · 第 41, 43, 425 行 -
账号、密钥或授权
使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。
主文档提及 · 第 28, 31, 33, 72, 76 行
文档引用的域名或地址
这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。
- localhost
- myapp.com
安全评级与访问范围
safe · 静态证据核验,不代表运行安全保证。
使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。
用户讨论
还没有已核实的点评。