是的,安卓上的Chrome浏览器支持使用Webauthn / FIDO2进行安全密钥的用户验证。
以下是一个使用Webauthn进行用户验证的基本示例代码:
// 检查浏览器是否支持Webauthn
if (!window.PublicKeyCredential) {
console.log("浏览器不支持Webauthn");
return;
}
// 创建一个Webauthn请求
const createCredentialOptions = {
publicKey: {
rp: {
name: "示例服务",
id: "example.com",
},
user: {
id: new Uint8Array([1, 2, 3, 4, 5]), // 用户唯一标识符
name: "user@example.com",
displayName: "示例用户",
},
challenge: new Uint8Array([6, 7, 8, 9, 0]), // 用于防止重放攻击的随机挑战
pubKeyCredParams: [
{ type: "public-key", alg: -7 }, // 使用ES256算法
],
timeout: 60000, // 超时时间(毫秒)
attestation: "direct", // 直接返回认证信息
},
};
// 发起Webauthn注册请求
navigator.credentials
.create(createCredentialOptions)
.then((newCredentialInfo) => {
console.log("Webauthn注册成功", newCredentialInfo);
})
.catch((error) => {
console.log("Webauthn注册失败", error);
});
// 创建一个Webauthn登录请求
const getAssertionOptions = {
publicKey: {
challenge: new Uint8Array([6, 7, 8, 9, 0]), // 用于防止重放攻击的随机挑战
allowCredentials: [
{
type: "public-key",
id: new Uint8Array([1, 2, 3, 4, 5]), // 之前注册时生成的唯一标识符
},
],
timeout: 60000, // 超时时间(毫秒)
},
};
// 发起Webauthn登录请求
navigator.credentials
.get(getAssertionOptions)
.then((assertion) => {
console.log("Webauthn登录成功", assertion);
})
.catch((error) => {
console.log("Webauthn登录失败", error);
});
在上面的示例中,createCredentialOptions
用于创建Webauthn注册请求,getAssertionOptions
用于创建Webauthn登录请求。您可以根据实际需求自定义这些选项。成功的注册请求将返回一个包含新的安全密钥信息的PublicKeyCredential
对象,成功的登录请求将返回一个包含登录凭据的PublicKeyCredential
对象。
请注意,为了在安卓上使用Webauthn,您需要使用支持FIDO2的安全密钥(例如YubiKey等)或支持生物识别(例如指纹或面部识别)的设备。