PublicKeyCredential: toJSON() 方法
PublicKeyCredential 接口的 toJSON() 方法返回一个 PublicKeyCredential 的 JSON 类型表示。
返回对象的属性取决于凭证是由 navigator.credentials.create() 在创建密钥对并注册用户时返回的,还是由 navigator.credentials.get() 在验证用户时返回的。
当 Web 应用代码调用 JSON.stringify() 来序列化 PublicKeyCredential 以便在注册或验证用户时发送到信赖方服务器时,此方法会被自动调用。它不打算在 Web 应用代码中直接调用。
语法
toJSON()
参数
无。
返回值
PublicKeyCredential 对象的 JSON 类型表示。
包含的属性取决于凭证是在注册时由 navigator.credentials.create() 返回的,还是在验证用户时由 navigator.credentials.get() 返回的。包含属性的值和类型与 PublicKeyCredential 相同,不同之处在于使用 base64url 编码的字符串来代替 buffer 属性。
对象属性包括:
id-
PublicKeyCredential.id返回的值。 rawId-
PublicKeyCredential.rawId的 base64url 编码版本。 authenticatorAttachment可选type-
字符串
"public-key"。 clientExtensionResults-
一个数组,包含
PublicKeyCredential.getClientExtensionResults()返回的值的 base64url 编码版本。 response-
response 属性对象取决于凭证是在注册操作还是认证操作后返回的。
-
在注册新用户时,
response将是AuthenticatorAttestationResponse的 JSON 类型表示,其中 buffer 值已被 base64url 编码。 -
在验证用户时,返回的值将是
AuthenticatorAssertionResponse的 JSON 类型表示版本,其中 buffer 值已被 base64url 编码。
-
异常
SecurityErrorDOMException-
RP 域无效。
示例
在注册新用户时,信赖方服务器会将有关预期凭证的信息提供给 Web 应用。Web 应用使用收到的信息(如下面的 createCredentialOptions)调用 navigator.credentials.create(),该调用返回一个以新的凭证(一个 PublicKeyCredential)完成的 Promise。
const newCredentialInfo = await navigator.credentials.create({
createCredentialOptions,
});
然后,Web 应用使用 JSON.stringify()(这反过来会调用 toJSON())序列化返回的凭证,并将其发布回服务器。
const registration_url = "https://example.com/registration";
const apiRegOptsResp = await fetch(registration_url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newCredentialInfo), // Calls newCredentialInfo.toJSON
});
规范
| 规范 |
|---|
| Web Authentication:访问公钥凭证的 API - 第 3 级 # dom-publickeycredential-tojson |
浏览器兼容性
加载中…