Passkey: 账户设置绑定 + 免密登录(WebAuthn)
- 引入 go-webauthn, Passkey 表存凭据, challenge 会话内存存储(带过期) - API: /webauthn/register|login begin/complete, /webauthn/passkeys 列表/删除 - 配置 OT_WEBAUTHN_RP_ID/RP_ORIGIN/RP_NAME;登录成功发 JWT+refresh cookie - 前端 lib/webauthn(编解码+凭据序列化+安全上下文检测), 账户设置绑定区, 登录页免密按钮 - 需 HTTPS 或 localhost(安全上下文) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
// WebAuthn(passkey)浏览器侧工具:选项编解码 + 凭据序列化。
|
||||
// go-webauthn 返回的 challenge/id 为 base64url 字符串,浏览器需要 ArrayBuffer;
|
||||
// 回调的 credential 需要把 ArrayBuffer 字段转回 base64url。
|
||||
|
||||
export function bufToB64url(buf: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buf)
|
||||
let s = ''
|
||||
for (const b of bytes) s += String.fromCharCode(b)
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
|
||||
}
|
||||
|
||||
export function b64urlToBuf(s: string): ArrayBuffer {
|
||||
const t = s.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const pad = t.length % 4 === 0 ? '' : '='.repeat(4 - (t.length % 4))
|
||||
const bin = atob(t + pad)
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
return bytes.buffer
|
||||
}
|
||||
|
||||
interface CredentialId {
|
||||
type?: string
|
||||
id: string
|
||||
}
|
||||
|
||||
function prepareIds(list?: CredentialId[]): { type?: string; id: ArrayBuffer }[] | undefined {
|
||||
if (!list) return undefined
|
||||
return list.map((c) => ({ ...c, id: b64urlToBuf(c.id) }))
|
||||
}
|
||||
|
||||
// registerPasskey 调用 navigator.credentials.create,返回可提交后端的 JSON。
|
||||
export async function registerPasskey(options: Record<string, any>): Promise<Record<string, any>> {
|
||||
const pk: Record<string, any> = { ...options.publicKey }
|
||||
pk.challenge = b64urlToBuf(pk.challenge)
|
||||
if (pk.user?.id) pk.user = { ...pk.user, id: b64urlToBuf(pk.user.id) }
|
||||
pk.excludeCredentials = prepareIds(pk.excludeCredentials)
|
||||
|
||||
const cred = (await navigator.credentials.create({ publicKey: pk as PublicKeyCredentialCreationOptions })) as PublicKeyCredential
|
||||
const resp = cred.response as AuthenticatorAttestationResponse
|
||||
return {
|
||||
id: cred.id,
|
||||
rawId: bufToB64url(cred.rawId),
|
||||
type: cred.type,
|
||||
response: {
|
||||
clientDataJSON: bufToB64url(resp.clientDataJSON),
|
||||
attestationObject: bufToB64url(resp.attestationObject),
|
||||
transports: (resp as unknown as { getTransports?: () => string[] }).getTransports?.() ?? [],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// loginPasskey 调用 navigator.credentials.get,返回可提交后端的 JSON。
|
||||
export async function loginPasskey(options: Record<string, any>): Promise<Record<string, any>> {
|
||||
const pk: Record<string, any> = { ...options.publicKey }
|
||||
pk.challenge = b64urlToBuf(pk.challenge)
|
||||
pk.allowCredentials = prepareIds(pk.allowCredentials)
|
||||
|
||||
const cred = (await navigator.credentials.get({ publicKey: pk as PublicKeyCredentialRequestOptions })) as PublicKeyCredential
|
||||
const resp = cred.response as AuthenticatorAssertionResponse
|
||||
return {
|
||||
id: cred.id,
|
||||
rawId: bufToB64url(cred.rawId),
|
||||
type: cred.type,
|
||||
response: {
|
||||
clientDataJSON: bufToB64url(resp.clientDataJSON),
|
||||
authenticatorData: bufToB64url(resp.authenticatorData),
|
||||
signature: bufToB64url(resp.signature),
|
||||
userHandle: resp.userHandle ? bufToB64url(resp.userHandle) : null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// isWebAuthnSupported 是否处于安全上下文(passkey 需要 HTTPS 或 localhost)。
|
||||
export function isWebAuthnSupported(): boolean {
|
||||
return typeof navigator !== 'undefined' && !!navigator.credentials && window.isSecureContext
|
||||
}
|
||||
@@ -29,7 +29,9 @@ export const useAuthStore = defineStore('auth', {
|
||||
},
|
||||
async login(username: string, password: string) {
|
||||
const { data } = await http.post('/auth/login', { username, password })
|
||||
const d = data.data as { access_token: string; user: User }
|
||||
this.setSession(data.data)
|
||||
},
|
||||
setSession(d: { access_token: string; user: User }) {
|
||||
this.accessToken = d.access_token
|
||||
this.user = d.user
|
||||
localStorage.setItem('ot_access', d.access_token)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { PhFingerprint } from '@phosphor-icons/vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { errMsg } from '@/api/client'
|
||||
import { http, errMsg } from '@/api/client'
|
||||
import { loginPasskey, isWebAuthnSupported } from '@/lib/webauthn'
|
||||
import Button from '@/components/ui/Button.vue'
|
||||
import Input from '@/components/ui/Input.vue'
|
||||
import ThemeToggle from '@/components/ui/ThemeToggle.vue'
|
||||
@@ -16,6 +18,7 @@ const toast = useToastStore()
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const loading = ref(false)
|
||||
const pkLoading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
async function submit() {
|
||||
@@ -33,6 +36,34 @@ async function submit() {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function passkeyLogin() {
|
||||
if (!isWebAuthnSupported()) {
|
||||
toast.err('当前环境不支持 Passkey(需 HTTPS 或 localhost)')
|
||||
return
|
||||
}
|
||||
pkLoading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const { data } = await http.post('/webauthn/login/begin', {
|
||||
username: username.value || undefined,
|
||||
})
|
||||
const credential = await loginPasskey(data.data.assertion)
|
||||
const resp = await http.post('/webauthn/login/complete', {
|
||||
challenge: data.data.challenge,
|
||||
credential,
|
||||
user_id: data.data.user_id ?? 0,
|
||||
})
|
||||
auth.setSession(resp.data.data)
|
||||
toast.ok('登录成功')
|
||||
const redirect = (route.query.redirect as string) || '/console/dashboard'
|
||||
router.push(redirect)
|
||||
} catch (e) {
|
||||
error.value = errMsg(e)
|
||||
} finally {
|
||||
pkLoading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -52,6 +83,15 @@ async function submit() {
|
||||
<Input v-model="password" label="密码" type="password" autocomplete="current-password" />
|
||||
<p v-if="error" class="text-xs text-err">{{ error }}</p>
|
||||
<Button class="w-full" :loading="loading" type="submit">登录</Button>
|
||||
<div class="flex items-center gap-3 py-1">
|
||||
<div class="h-px flex-1 bg-edge" />
|
||||
<span class="text-xs text-muted">或</span>
|
||||
<div class="h-px flex-1 bg-edge" />
|
||||
</div>
|
||||
<Button variant="ghost" class="w-full" :loading="pkLoading" type="button" @click="passkeyLogin">
|
||||
<PhFingerprint :size="15" />
|
||||
使用 Passkey 登录
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<p class="mt-5 text-center text-sm text-muted">
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { PhFingerprint } from '@phosphor-icons/vue'
|
||||
import { http, errMsg } from '@/api/client'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { fmtMoney, fmtTime } from '@/lib/format'
|
||||
import { registerPasskey, isWebAuthnSupported } from '@/lib/webauthn'
|
||||
import Badge from '@/components/ui/Badge.vue'
|
||||
import Button from '@/components/ui/Button.vue'
|
||||
import Input from '@/components/ui/Input.vue'
|
||||
@@ -11,6 +13,54 @@ import Input from '@/components/ui/Input.vue'
|
||||
const auth = useAuthStore()
|
||||
const toast = useToastStore()
|
||||
|
||||
const passkeys = ref<{ id: number; name: string; created_at: string }[]>([])
|
||||
const binding = ref(false)
|
||||
|
||||
async function loadPasskeys() {
|
||||
try {
|
||||
const { data } = await http.get('/webauthn/passkeys')
|
||||
passkeys.value = data.data.items
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
async function bindPasskey() {
|
||||
if (!isWebAuthnSupported()) {
|
||||
toast.err('当前环境不支持 Passkey(需 HTTPS 或 localhost)')
|
||||
return
|
||||
}
|
||||
binding.value = true
|
||||
try {
|
||||
const { data } = await http.post('/webauthn/register/begin')
|
||||
const credential = await registerPasskey(data.data.creation)
|
||||
await http.post('/webauthn/register/complete', {
|
||||
challenge: data.data.challenge,
|
||||
name: 'passkey',
|
||||
credential,
|
||||
})
|
||||
toast.ok('Passkey 已绑定')
|
||||
await loadPasskeys()
|
||||
} catch (e) {
|
||||
toast.err(errMsg(e))
|
||||
} finally {
|
||||
binding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removePasskey(id: number) {
|
||||
if (!confirm('解除该 Passkey?解除后需重新绑定才能免密登录。')) return
|
||||
try {
|
||||
await http.delete(`/webauthn/passkeys/${id}`)
|
||||
toast.ok('已解除')
|
||||
await loadPasskeys()
|
||||
} catch (e) {
|
||||
toast.err(errMsg(e))
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadPasskeys)
|
||||
|
||||
const oldPwd = ref('')
|
||||
const newPwd = ref('')
|
||||
const confirmPwd = ref('')
|
||||
@@ -80,5 +130,26 @@ async function changePassword() {
|
||||
<Button :loading="saving" @click="changePassword">更新密码</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card p-5">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold">Passkey 登录</h2>
|
||||
<Button size="sm" :loading="binding" @click="bindPasskey">
|
||||
<PhFingerprint :size="14" />
|
||||
绑定 Passkey
|
||||
</Button>
|
||||
</div>
|
||||
<p class="mb-3 text-xs text-muted">用生物识别或系统 PIN 免密登录。需要 HTTPS 或 localhost 环境。</p>
|
||||
<ul v-if="passkeys.length" class="divide-y divide-edge">
|
||||
<li v-for="pk in passkeys" :key="pk.id" class="flex items-center justify-between py-2">
|
||||
<div>
|
||||
<p class="text-sm text-ink">{{ pk.name }}</p>
|
||||
<p class="font-mono text-xs text-muted">{{ fmtTime(pk.created_at) }}</p>
|
||||
</div>
|
||||
<button class="text-xs text-muted transition hover:text-err" @click="removePasskey(pk.id)">解除</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-xs text-muted">尚未绑定 Passkey</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user