使用文档

网站通过使用通行密钥代替密码,可提高用户帐号的安全性并简化用户帐号的管理和使用。借助通行密钥,用户可以使用设备的屏幕锁定功能(例如指纹锁、人脸识别锁或设备 PIN 码)来登录网站或应用。必须先创建通行密钥、将其与用户帐号关联,并将其公钥存储在服务器上,之后用户才能使用该通行密钥进行登录。

示例

示例网站

代码实现

前端代码

安装依赖库

1
npm install @simplewebauthn/browser

后端需实现的接口

注册验证器

1
2
3
从依赖方(您的服务器)获取注册选项 (/passkey/generate-registration-options)
将身份验证者的回复提交给依赖方进行验证 (/passkey/verify-registration)

使用验证器

1
2
从依赖方(您的服务器)获取身份验证选项 (/passkey/generate-authentication-options)
将身份验证者的回复提交给依赖方进行验证 (/passkey/verify-authentication)

示例代码

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<template>
<div class="container">
<el-input
v-model.trim="state.uniid"
style="width: 300px"
placeholder="请输入用户唯一标识符/邮箱账号"
/>
<el-button @click="init" :disabled="!state.uniid">创建通行密钥</el-button>
<el-button @click="login">通过通行密钥登录</el-button>
</div>
</template>
<script setup lang="ts">
import {
reactive,
onMounted,
getCurrentInstance,
type ComponentInternalInstance,
} from "vue";
import {
startRegistration,
startAuthentication,
} from "@simplewebauthn/browser";
import { ElMessage } from "element-plus";
const currentInstance = getCurrentInstance() as ComponentInternalInstance;
const { $UtilsHttp } = currentInstance.appContext.config.globalProperties;
const state = reactive({
uniid: "",
});
const init = async () => {
try {
const { result } = await $UtilsHttp(
"/passkey/generate-registration-options",
"get",
{
uniid: state.uniid,
}
);
const challenge = result.challenge;
let attResp;
try {
attResp = await startRegistration(result);
} catch (error) {
if (error.name === "InvalidStateError") {
ElMessage.error(
"Authenticator was probably already registered by user"
);
} else {
ElMessage.error(error.toString());
}
throw error;
}
try {
const { result } = await $UtilsHttp(
"/passkey/verify-registration",
"post",
{
attResp,
challenge,
}
);
if (result) ElMessage.success("已成功添加通行密钥(PassKey)!");
} catch (error) {
ElMessage.error(error.response.data.error);
}
} catch (error) {
ElMessage.error(error.response.data.message);
}
};
const login = async () => {
const { result } = await $UtilsHttp(
"/passkey/generate-authentication-options",
"get"
);
const challenge = result.challenge;
let asseResp;
try {
asseResp = await startAuthentication(result);
} catch (error) {
ElMessage.error(error.toString());
throw error;
}
try {
const {
result: { flag, token },
} = await $UtilsHttp("/passkey/verify-authentication", "post", {
asseResp,
challenge,
});
if (flag) ElMessage.success("使用通行密钥(PassKey)登录成功!!");
} catch (error) {
ElMessage.error(error.response.data.message);
}
};
onMounted(() => {});
</script>
<style lang="less" scoped></style>

后端代码

安装依赖库

1
npm install @simplewebauthn/server