PublicKeyCredential:parseCreationOptionsFromJSON() 靜態方法

基準線 2025
新推出

自 ⁨2025 年 3 月⁩ 起,此功能可在最新的裝置和瀏覽器版本上使用。此功能可能在舊裝置或瀏覽器上無法正常工作。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

parseCreationOptionsFromJSON() 靜態方法是 PublicKeyCredential 介面的一個方法,它根據其屬性的 JSON 表示形式建立一個 PublicKeyCredentialCreationOptions 物件。

該方法是一個方便的函式,用於將依賴方伺服器提供的使用憑證選項資訊轉換為 Web 應用可以用於 建立憑證 的格式。

語法

js
PublicKeyCredential.parseCreationOptionsFromJSON(options)

引數

options

一個與 PublicKeyCredentialCreationOptions 結構相同的物件,但其中 buffer 屬性使用 base64url 編碼的字串替代。

返回值

一個 PublicKeyCredentialCreationOptions 物件。

異常

EncodingError DOMException

如果 `options` 物件無法轉換為 PublicKeyCredentialCreationOptions 物件,則會丟擲錯誤。

SecurityError DOMException

RP 域無效。

描述

用於 建立金鑰對和註冊使用者 的 Web 身份驗證過程涉及依賴方伺服器向 Web 應用傳送建立憑證所需的資訊,包括使用者身份、依賴方以及“挑戰”的詳細資訊。Web 應用透過將 PublicKeyCredentialCreationOptions 物件作為引數傳遞給 navigator.credentials.create() 來將此資訊傳遞給認證器以建立憑證。

該規範並未定義傳送建立憑證所需資訊的具體方式。一種方便的方法是讓伺服器將資訊封裝在一個 JSON 型別表示 中,該表示形式模仿 PublicKeyCredentialCreationOptions 物件的結構,但將 `challenge` 和 `user.id` 等 buffer 屬性編碼為 base64url 字串。此物件可以序列化為 JSON 字串,傳送到 Web 應用並反序列化,然後使用 **parseCreationOptionsFromJSON()** 轉換為 PublicKeyCredentialCreationOptions 物件。

示例

在註冊新使用者時,依賴方伺服器會向 Web 應用提供有關預期憑證的資訊。下面的程式碼定義了該資訊,其形式如上文 options 引數中所述(取自 AuthenticatorResponse 中的 “獲取 AuthenticatorAttestationResponse”)。

js
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 應用。

js
JSON.stringify(createCredentialOptionsJSON);

Web 應用可以將 JSON 字串反序列化回 `createCredentialOptionsJSON` 物件(此處未顯示)。**parseCreationOptionsFromJSON()** 方法用於將該物件轉換為可用於 `navigator.credentials.create()` 的格式。

js
// 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

瀏覽器相容性

另見