WebAuthn 常被说成“无密码登录”,但真正接入后会发现,它更像一套独立于账号密码的认证协议:注册和登录都需要服务端生成 Challenge,浏览器调用系统 Passkey,后端验证签名和 Origin。
这篇文章用一个 Go 后端和一个 React 前端,把 WebAuthn 的注册、登录、Challenge 存储、凭证管理和常见坑串起来。
1. 先理解 WebAuthn 里的几个概念
RP ID
RP ID 是当前站点的有效域名,例如:
它不包含协议和端口。
Origin
Origin 是浏览器实际访问的完整来源,例如:
1
| https://admin.example.com
|
本地开发:
localhost 被视为安全上下文,可以使用 WebAuthn;但不要混用 localhost 和 127.0.0.1,否则 Origin 不匹配。
Challenge
Challenge 是服务端为每次注册/登录生成的一次性随机数。
浏览器会让 Passkey 对 Challenge 签名,服务端再验证:
1 2 3 4 5
| Challenge 是否由本服务生成 是否过期 是否已经使用过 签名是否覆盖这个 Challenge Origin / RP ID 是否正确
|
没有 Challenge,攻击者可以重放旧的 WebAuthn 响应。
Discoverable Credential
普通 WebAuthn 登录可以先输入用户名,再告诉浏览器去用哪个凭证。
Discoverable Credential 反过来:
1 2 3 4
| 不输入用户名 allowCredentials = [] 浏览器展示系统 Passkey 选择器 服务端根据 credential ID 反查账号
|
这就是常说的“无用户名 Passkey 登录”。
2. 整体流程
注册
1 2 3 4 5 6
| 账号密码登录后台 → 输入当前密码确认 → POST /webauthn/register/begin → 浏览器 navigator.credentials.create → POST /webauthn/register/finish → 保存凭证
|
登录
1 2 3 4 5
| 点击“使用通行密钥登录” → POST /webauthn/login/begin → 浏览器 navigator.credentials.get → POST /webauthn/login/finish → 服务端反查账号并签发 JWT
|
账号密码登录保持原样,WebAuthn 只是另一条登录路径。
3. Go 后端依赖
1
| go get github.com/go-webauthn/webauthn
|
初始化:
1 2 3 4 5 6 7 8 9 10 11 12 13
| package auth
import ( "github.com/go-webauthn/webauthn/webauthn" )
func NewWebAuthn() (*webauthn.WebAuthn, error) { return webauthn.New(&webauthn.Config{ RPDisplayName: "Ten Admin", RPID: "localhost", RPOrigins: []string{"http://localhost:3000"}, }) }
|
生产环境必须换成真实域名,并使用 HTTPS。
4. 数据模型
账号
1 2 3 4 5
| type Account struct { ID int64 Username string Status int8 }
|
凭证
1 2 3 4 5 6 7 8 9 10 11 12 13
| type WebAuthnCredential struct { ID int64 AccountID int64 CredentialID []byte PublicKey []byte SignCount uint32 Transports string AAGUID []byte Name string CloneWarning bool CreatedAt time.Time LastUsedAt *time.Time }
|
credential_id 必须唯一索引。
这里不增加 webauthn_enabled 字段,直接看账号有没有凭证:
1 2
| 有凭证 = 已启用 Passkey 无凭证 = 未启用 Passkey
|
避免账号字段和凭证表出现状态不一致。
5. 实现 webauthn.User
go-webauthn 需要一个 User:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| type WebAuthnUser struct { Account *Account Credentials []webauthn.Credential }
func (u *WebAuthnUser) WebAuthnID() []byte { buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, uint64(u.Account.ID)) return buf }
func (u *WebAuthnUser) WebAuthnName() string { return u.Account.Username }
func (u *WebAuthnUser) WebAuthnDisplayName() string { return u.Account.Username }
func (u *WebAuthnUser) WebAuthnCredentials() []webauthn.Credential { return u.Credentials }
|
user handle 使用账号 ID 的稳定字节表示。
6. Challenge 存储
Challenge 不能放前端,也不能信任前端回传的 Challenge。
服务端保存:
1 2 3 4 5 6
| type CeremonySession struct { Purpose string AccountID int64 SessionData webauthn.SessionData ExpiresAt time.Time }
|
缓存 Key:
1 2 3
| webauthn:login:<ticket> webauthn:register:<ticket> webauthn:stepup:<ticket>
|
规则:
- TTL 5 分钟
- 一次性消费
- 成功后删除
- 生产多实例使用 Redis
- 单机可以用内存缓存
前端只拿到 ticket,Challenge 留在服务端。
7. 注册流程
7.1 密码确认
注册 Passkey 是敏感操作,先要求用户再次输入密码。
1
| POST /webauthn/register/step-up
|
验证通过后返回:
1 2 3
| { "stepUpTicket": "opaque-ticket" }
|
这个接口不能记录请求体,否则密码会进入操作审计日志。
7.2 Begin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| func (h *Handler) BeginRegistration(w http.ResponseWriter, r *http.Request) { user := currentUser(r)
var req struct { StepUpTicket string `json:"stepUpTicket"` Name string `json:"name"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return }
if !h.stepUp.Valid(r.Context(), req.StepUpTicket, user.ID) { http.Error(w, "invalid step-up ticket", http.StatusForbidden) return }
if h.credentials.Count(r.Context(), user.ID) >= h.maxCredentials { http.Error(w, "credential limit", http.StatusBadRequest) return }
options, session, err := h.webauthn.BeginRegistration( user, webauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementRequired), ) if err != nil { http.Error(w, "begin registration failed", http.StatusInternalServerError) return }
ticket := randomTicket() h.store.Save(r.Context(), "webauthn:register:"+ticket, CeremonySession{ Purpose: "register", AccountID: user.Account.ID, SessionData: *session, ExpiresAt: time.Now().Add(5 * time.Minute), })
json.NewEncoder(w).Encode(map[string]any{ "ticket": ticket, "publicKey": options.Response, }) }
|
residentKey=required 是 Passkey 无用户名登录的前提。
7.3 Finish
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| func (h *Handler) FinishRegistration(w http.ResponseWriter, r *http.Request) { ticket := r.Header.Get("X-WebAuthn-Ticket") session, ok := h.store.Take(r.Context(), "webauthn:register:"+ticket) if !ok || session.ExpiresAt.Before(time.Now()) { http.Error(w, "challenge expired", http.StatusBadRequest) return }
user := loadWebAuthnUser(r.Context(), session.AccountID)
credential, err := h.webauthn.FinishRegistration(user, session.SessionData, r) if err != nil { http.Error(w, "registration failed", http.StatusBadRequest) return }
if err := h.credentials.Save(r.Context(), user.Account.ID, credential); err != nil { http.Error(w, "save credential failed", http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent) }
|
注意:
- Finish 时要再次校验凭证数量,防止并发注册超限。
credential.ID 必须唯一。- 保存
PublicKey、SignCount、Transports、AAGUID。
8. 无用户名登录
8.1 Begin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| func (h *Handler) BeginLogin(w http.ResponseWriter, r *http.Request) { options, session, err := h.webauthn.BeginDiscoverableLogin() if err != nil { http.Error(w, "begin login failed", http.StatusInternalServerError) return }
ticket := randomTicket() h.store.Save(r.Context(), "webauthn:login:"+ticket, CeremonySession{ Purpose: "login", SessionData: *session, ExpiresAt: time.Now().Add(5 * time.Minute), })
json.NewEncoder(w).Encode(map[string]any{ "ticket": ticket, "publicKey": options.Response, }) }
|
响应中的 allowCredentials 应为空,浏览器才会展示系统 Passkey 选择器。
8.2 Finish
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| func (h *Handler) FinishLogin(w http.ResponseWriter, r *http.Request) { ticket := r.Header.Get("X-WebAuthn-Ticket") session, ok := h.store.Take(r.Context(), "webauthn:login:"+ticket) if !ok || session.ExpiresAt.Before(time.Now()) { http.Error(w, "challenge expired", http.StatusBadRequest) return }
handler := func(rawID, userHandle []byte) (webauthn.User, error) { credential, account, err := h.credentials.FindByCredentialID(r.Context(), rawID) if err != nil { return nil, err } if account.Status != StatusEnabled { return nil, errors.New("account disabled") } return loadWebAuthnUserWithCredential(account, credential), nil }
credential, err := h.webauthn.FinishDiscoverableLogin(handler, session.SessionData, r) if err != nil { http.Error(w, "passkey login failed", http.StatusUnauthorized) return }
account := h.credentials.AccountByCredential(r.Context(), credential.ID) h.credentials.UpdateSignCount(r.Context(), credential.ID, credential.Authenticator.SignCount)
result, err := h.sessions.Issue(account) if err != nil { http.Error(w, "issue token failed", http.StatusInternalServerError) return }
json.NewEncoder(w).Encode(result) }
|
登录成功后再走原有 session / JWT 签发逻辑。密码登录和 Passkey 登录共用同一个签发方法,但协议入口独立。
9. React 前端
安装:
1
| npm i @simplewebauthn/browser
|
9.1 登录按钮
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import { startAuthentication } from '@simplewebauthn/browser'
async function loginWithPasskey() { const begin = await fetch('/api/webauthn/login/begin', { method: 'POST', }).then((res) => res.json())
const credential = await startAuthentication({ optionsJSON: begin.publicKey, })
const result = await fetch('/api/webauthn/login/finish', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WebAuthn-Ticket': begin.ticket, }, body: JSON.stringify(credential), }).then((res) => res.json())
localStorage.setItem('token', result.token) }
|
9.2 注册 Passkey
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import { startRegistration } from '@simplewebauthn/browser'
async function registerPasskey(password: string) { const stepUp = await fetch('/api/webauthn/register/step-up', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }), }).then((res) => res.json())
const begin = await fetch('/api/webauthn/register/begin', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ stepUpTicket: stepUp.stepUpTicket, name: '我的 Passkey', }), }).then((res) => res.json())
const credential = await startRegistration({ optionsJSON: begin.publicKey, })
await fetch('/api/webauthn/register/finish', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WebAuthn-Ticket': begin.ticket, }, body: JSON.stringify(credential), }) }
|
startRegistration 和 startAuthentication 必须在用户点击等手势中调用,不能页面加载后自动执行。
10. 安全控制
Origin 和 RP ID
rpID 不包含端口rpOrigins 包含协议和端口- 本地
http://localhost:3000 可用 - 生产必须 HTTPS
- 不要混用
localhost 和 127.0.0.1
Challenge
- 5 分钟过期
- 一次性消费
- 不交给前端保存
- 生产多实例用 Redis 共享
- 单机可以用内存缓存
SignCount
1 2 3
| signCount 增加:正常 signCount 不变:允许,很多同步 Passkey 不递增 signCount 减少:拒绝,记录 clone_warning
|
账号状态
Passkey 验证成功后仍然要检查:
错误信息
登录失败统一返回:
不要告诉客户端是“账号不存在”还是“凭证不存在”。
11. 管理员和恢复策略
清空 Passkey
管理员接口:
1
| DELETE /api/accounts/{id}/webauthn/credentials
|
使用独立权限:
重置密码
管理员重置密码时,建议同时清空该账号全部 Passkey:
1 2 3
| 更新密码 → revoke 全部 session → 删除全部 Passkey
|
因为重置密码通常意味着账号恢复,旧设备上的 Passkey 不应该继续有效。
用户自己修改密码时,可以保留 Passkey。
12. 本地测试
访问:
不要用:
配置:
1 2
| RPID=localhost RPOrigins=http://localhost:3000
|
Chrome 控制台检查:
1 2 3
| window.isSecureContext window.PublicKeyCredential navigator.credentials
|
都正常时,点击按钮才会弹出系统 Passkey 选择器。
13. 总结
WebAuthn 的难点不在浏览器 API,而在服务端状态管理:
1 2 3 4 5
| Challenge 要服务端保存 Ticket 要一次性 RP ID / Origin 要严格匹配 凭证要能按 credential ID 反查账号 登录成功后再签发 session/JWT
|
密码登录和 Passkey 登录可以是两条独立路径:
1 2
| 账号密码登录:保留 Passkey 登录:用户主动选择
|
这样既不破坏现有登录体系,也能让用户逐步迁移到 Passkey。