---
title: "Passkeys 与 WebAuthn:无密码登录的部署与回退策略"
keywords:
- Passkeys
- WebAuthn
- FIDO2
- PublicKeyCredential
- RP ID
- userVerification
- 平台认证器
- 跨设备
description: "介绍 Passkeys/WebAuthn 的无密码登录方案与端到端部署要点,涵盖注册与登录流程、平台认证器特性、跨设备同步与回退策略,并给出验证与安全注意事项。"
categories:
- 应用软件
- 安全杀毒
---
概述
Passkeys 基于 WebAuthn/FIDO2,在平台认证器(如操作系统钥匙串)中存储私钥,通过浏览器调用 navigator.credentials.create/get 完成注册与登录,提供更强的抗钓鱼与更佳的用户体验。部署需兼顾 RP ID、用户验证等级、跨设备同步能力与回退(如密码/OTP)。
机制与用法
注册(Create)示例
// 服务端生成挑战与注册选项(示意),返回到前端
const publicKey = {
challenge: Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(32))),
rp: { name: 'Example Inc', id: 'example.com' },
user: {
id: Uint8Array.from('user-123', c => c.charCodeAt(0)),
name: '[email protected]',
displayName: 'User 123'
},
pubKeyCredParams: [
{ type: 'public-key', alg: -7 }, // ES256
{ type: 'public-key', alg: -257 } // RS256
],
authenticatorSelection: {
authenticatorAttachment: 'platform', // 优先平台认证器以启用 Passkeys
residentKey: 'preferred',
requireResidentKey: false,
userVerification: 'required'
},
attestation: 'none'
}
const cred = await navigator.credentials.create({ publicKey })
// 将 cred.rawId、cred.response.attestationObject、clientDataJSON 上传服务端完成验证与存储
登录(Get)示例
const requestOptions = {
challenge: Uint8Array.from(window.crypto.getRandomValues(new Uint8Array(32))),
rpId: 'example.com',
userVerification: 'required',
allowCredentials: [
// 可选:指定历史注册的 credentialId
// { type: 'public-key', id: Uint8Array.from([...]) }
]
}
const assertion = await navigator.credentials.get({ publicKey: requestOptions })
// 上传 authData、signature、clientDataJSON、rawId 供服务端验证签名
服务端要点
- RP ID 必须与站点有效域匹配(子域需谨慎);存储
credentialId与公钥用于后续登录验签。 - 验签与数据结构复杂,建议使用成熟库(如基于 FIDO2/WebAuthn 的验证库)并妥善校验
challenge/origin/rpId/userHandle等字段。 - 账户恢复与跨设备:启用平台生态的 Passkeys 同步(如 iCloud/Google),并提供安全回退(邮箱 OTP/客服流程)。
工程建议
- UX:优先展示 Passkeys,登录失败或不支持时自动回退到密码/OTP;清晰指示设备支持情况。
- 安全:启用
userVerification='required'以结合生物识别;对clientDataJSON的type/origin/challenge做严格校验;防重放与绑定会话。 - 兼容:支持跨源 iframe 需配置
Permissions-Policy: publickey-credentials-get=()|*视场景;对不支持的浏览器提供回退。 - 监控:记录注册/登录成功率、失败原因、设备类型;关注不同平台的 UX 差异。
参考与验证
- W3C Web Authentication Level 2 规范:https://www.w3.org/TR/webauthn-2/
- MDN WebAuthn 文档:https://developer.mozilla.org/docs/Web/API/Web_Authentication_API
- web.dev Passkeys 指南:https://web.dev/passkeys/
- FIDO Alliance 资源:https://fidoalliance.org/

发表评论 取消回复