PublicKeyCredential:parseCreationOptionsFromJSON() 静态方法
parseCreationOptionsFromJSON() 静态方法是 PublicKeyCredential 接口的一个方法,它根据其属性的 JSON 表示形式创建一个 PublicKeyCredentialCreationOptions 对象。
该方法是一个方便的函数,用于将依赖方服务器提供的使用凭证选项信息转换为 Web 应用可以用于 创建凭证 的格式。
语法
PublicKeyCredential.parseCreationOptionsFromJSON(options)
参数
options-
一个与
PublicKeyCredentialCreationOptions结构相同的对象,但其中 buffer 属性使用 base64url 编码的字符串替代。
返回值
异常
EncodingErrorDOMException-
如果 `options` 对象无法转换为
PublicKeyCredentialCreationOptions对象,则会抛出错误。 SecurityErrorDOMException-
RP 域无效。
描述
用于 创建密钥对和注册用户 的 Web 身份验证过程涉及依赖方服务器向 Web 应用发送创建凭证所需的信息,包括用户身份、依赖方以及“挑战”的详细信息。Web 应用通过将 PublicKeyCredentialCreationOptions 对象作为参数传递给 navigator.credentials.create() 来将此信息传递给认证器以创建凭证。
该规范并未定义发送创建凭证所需信息的具体方式。一种方便的方法是让服务器将信息封装在一个 JSON 类型表示 中,该表示形式模仿 PublicKeyCredentialCreationOptions 对象的结构,但将 `challenge` 和 `user.id` 等 buffer 属性编码为 base64url 字符串。此对象可以序列化为 JSON 字符串,发送到 Web 应用并反序列化,然后使用 **parseCreationOptionsFromJSON()** 转换为 PublicKeyCredentialCreationOptions 对象。
示例
在注册新用户时,依赖方服务器会向 Web 应用提供有关预期凭证的信息。下面的代码定义了该信息,其形式如上文 options 参数中所述(取自 AuthenticatorResponse 中的 “获取 AuthenticatorAttestationResponse”)。
const createCredentialOptionsJSON = {
challenge:
"21, 31, 105, " /* 29 more random bytes generated by the server in this string */,
rp: {
name: "Example CORP",
id: "login.example.com",
},
user: {
id: "16",
name: "canand@example.com",
displayName: "Carina Anand",
},
pubKeyCredParams: [
{
type: "public-key",
alg: -7,
},
],
};
由于此对象仅使用 JSON 数据类型,因此可以使用 JSON.stringify() 将其序列化为 JSON 并发送到 Web 应用。
JSON.stringify(createCredentialOptionsJSON);
Web 应用可以将 JSON 字符串反序列化回 `createCredentialOptionsJSON` 对象(此处未显示)。**parseCreationOptionsFromJSON()** 方法用于将该对象转换为可用于 `navigator.credentials.create()` 的格式。
// Convert options to form used by create()
const createCredentialOptions =
PublicKeyCredential.parseCreationOptionsFromJSON(
createCredentialOptionsJSON, // JSON-type representation
);
navigator.credentials
.create({ publicKey: createCredentialOptions })
.then((newCredentialInfo) => {
// Handle the new credential information here.
})
.catch((err) => {
console.error(err);
});
规范
| 规范 |
|---|
| Web Authentication:访问公钥凭证的 API - 第 3 级 # dom-publickeycredential-parsecreationoptionsfromjson |
浏览器兼容性
加载中…