Web Authentication API 是一套由 W3C 和 FIDO 联盟制定的浏览器标准,它允许网站调用设备上的生物识别模块或硬件密钥,完成用户身份校验,从而彻底摆脱密码。其核心思想是借助公钥密码学,让服务器只保存公钥,而私钥永远不离开用户设备。

注册阶段的实现
注册时,服务器先生成一段随机挑战码,并返回给用户代理。浏览器调用 navigator.credentials.create() 触发设备生成密钥对,用户完成指纹或面容验证后,公钥和凭证 ID 被发回服务器存储。
前端注册代码
// 向服务器请求注册参数
const options = await fetch('/webauthn/register/options').then(r => r.json());
// 转换 base64 字段为 ArrayBuffer
options.challenge = Uint8Array.from(atob(options.challenge), c => c.charCodeAt(0));
options.user.id = Uint8Array.from(atob(options.user.id), c => c.charCodeAt(0));
// 调用 API 创建凭证
const credential = await navigator.credentials.create({ publicKey: options });
// 将凭证发送到服务器保存
await fetch('/webauthn/register', {
method: 'POST',
body: JSON.stringify(credential),
headers: { 'Content-Type': 'application/json' }
});
后端保存公钥示例
import json
from flask import request
@app.route('/webauthn/register', methods=['POST'])
def register():
data = json.loads(request.data)
# 提取公钥和凭证 ID 存入数据库
credential_id = data['rawId']
public_key = data['response']['attestationObject']
save_to_db(user_id, credential_id, public_key)
return {'status': 'ok'}
登录阶段的验证
登录时服务器下发挑战,前端用 navigator.credentials.get() 取出私钥签名,服务器用之前存的公钥验证签名是否正确,并核对挑战码防止重放。
const opt = await fetch('/webauthn/login/options').then(r => r.json());
opt.challenge = Uint8Array.from(atob(opt.challenge), c => c.charCodeAt(0));
const assertion = await navigator.credentials.get({ publicKey: opt });
await fetch('/webauthn/login', {
method: 'POST',
body: JSON.stringify(assertion),
headers: { 'Content-Type': 'application/json' }
});
常见误区与注意点
- 不要将
userVerification设为 preferred 却不做服务端强制,否则部分设备会跳过生物识别。 - rp.id 必须与当前域名一致,跨子域时要显式配置,否则浏览器拒绝调用 API。
- 公钥验签失败多数源于 base64 与 ArrayBuffer 转换错误,前后端编解码要统一。
无密码登录并不是去掉输入框那么简单,而是把信任根留在用户设备,服务器只认数学签名。
小结
通过 Web Authentication API 实现生物识别无密码登录,本质是用设备内私钥签名替代密码传输。只要正确配置依赖方信息、挑战码机制和用户验证等级,就能在网页端获得抗钓鱼、抗撞库的高安全登录体验。
Web_Authentication_API生物识别无密码登录修改时间:2026-07-31 10:54:21