JavaScript 用 Azure Key Vault 証明書クライアント ライブラリ - バージョン 4.8.0

Azure Key Vault は、クラウド アプリケーション全体で使用される証明書の安全なストレージと自動管理を提供するクラウド サービスです。 複数の証明書と同じ証明書の複数のバージョンを Azure Key Vaultに保持できます。 コンテナー内の各証明書には、証明書の発行と有効期間を制御するポリシーと、有効期限が近い証明書として実行されるアクションが関連付けられています。

Azure Key Vaultの詳細については、「Azure Key Vaultとは」を参照してください。

Node.js アプリケーションで Azure Key Vault 証明書のクライアント ライブラリを使用して、次の手順を実行します。

  • 証明書を取得、設定、削除します。
  • 証明書、その属性、発行者、ポリシー、操作、連絡先を更新します。
  • 証明書のバックアップと復元。
  • 削除された証明書を取得、消去、または回復します。
  • 証明書のすべてのバージョンを取得します。
  • すべての証明書を取得します。
  • 削除されたすべての証明書を取得します。

注: Azure Key Vault サービスの制限により、このパッケージをブラウザーで使用することはできません。ガイダンスについては、こちらのドキュメントを参照してください。

主要リンク:

はじめに

現在サポートされている環境

前提条件

パッケージをインストールする

npm を使用して Azure Key Vault 証明書クライアント ライブラリをインストールする

npm install @azure/keyvault-certificates

ID ライブラリをインストールする

Key Vaultクライアントは、Azure Id ライブラリを使用して認証します。 npm を使用してインストールする

npm install @azure/identity

TypeScript の構成

TypeScript ユーザーには、Node 型の定義がインストールされている必要があります。

npm install @types/node

tsconfig.jsonで有効にする compilerOptions.allowSyntheticDefaultImports 必要もあります。 が有効compilerOptions.esModuleInteropallowSyntheticDefaultImportsになっている場合は、既定で が有効になっていることに注意してください。 詳細については、「 TypeScript のコンパイラ オプション ハンドブック 」を参照してください。

Azure Active Directory での認証

Key Vault サービスは、API に対する要求を認証するために Azure Active Directory に依存しています。 @azure/identity パッケージには、アプリケーションでこれを行うために使用できるさまざまな資格情報の種類が用意されています。 README for @azure/identity には、作業を開始するための詳細とサンプルが用意されています。

Azure Key Vault サービスと対話するには、 クラスのインスタンス、コンテナーの CertificateClientURL、資格情報オブジェクトを作成する必要があります。 このドキュメントに示す例では、 という名前 DefaultAzureCredentialの資格情報オブジェクトを使用します。これは、ローカルの開発環境や運用環境など、ほとんどのシナリオに適しています。 さらに、運用環境での認証には マネージド ID を 使用することをお勧めします。

さまざまな認証方法と、それに対応する資格情報の種類の詳細については、 Azure Id のドキュメントを参照してください

簡単な例を次に示します。 最初に、 と をインポート DefaultAzureCredential します CertificateClient

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

これらをインポートしたら、次にキー コンテナー サービスに接続できます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

// Build the URL to reach your key vault
const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

// Lastly, create our certificates client and connect to the service
const client = new CertificateClient(url, credential);

主要な概念

  • Certificates クライアントは、JavaScript アプリケーションから Azure Key Vault API の証明書に関連する API メソッドを操作するためのプライマリ インターフェイスです。 初期化されると、証明書の作成、読み取り、更新、削除に使用できる基本的な一連のメソッドが提供されます。
  • 証明書のバージョンは、Key Vault内の証明書のバージョンです。 ユーザーが一意の証明書名に値を割り当てるたびに、その証明書の新しい バージョン が作成されます。 名前で証明書を取得すると、クエリに特定のバージョンが指定されていない限り、割り当てられた最新の値が常に返されます。
  • 論理的な削除 を使用すると、Key Vault は削除と消去を 2 つの別々の手順でサポートできるため、削除された証明書はすぐに失われるわけではありません。 これは、Key Vaultで論理的な削除が有効になっている場合にのみ発生します。
  • 証明書のバックアップは、作成された任意の証明書から生成できます。 これらのバックアップはバイナリ データとして提供され、以前に削除された証明書の再生成にのみ使用できます。

Azure Key Vault サービス API バージョンの指定

既定では、このパッケージでは最新の Azure Key Vault サービス バージョンが使用されます。これは です7.1。 サポートされている他のバージョンは のみです 7.0。 使用されているサービスのバージョンを変更するには、次に示すようにクライアント コンストラクターで オプション serviceVersion を設定します。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

// Change the Azure Key Vault service API version being used via the `serviceVersion` option
const client = new CertificateClient(url, credential, {
  serviceVersion: "7.0",
});

次のセクションでは、Azure Key Vault 証明書を使用する一般的なタスクの一部をカバーするコード スニペットを示します。 ここで説明するシナリオは、次で構成されます。

証明書の作成と設定

beginCreateCertificateは、Azure Key Vaultに格納される証明書を作成します。 同じ名前の証明書が既に存在する場合は、新しいバージョンの証明書が作成されます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  // Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
  await client.beginCreateCertificate(certificateName, {
    issuerName: "Self",
    subject: "cn=MyCert",
  });
}

main();

証明書の名前とポリシーに加えて、オプションの値を使用して 3 番目の引数に次のプロパティを渡すこともできます。

  • enabled: 証明書を使用できるかどうかを決定するブール値。
  • tags: 証明書の検索とフィルター処理に使用できる任意のキー値のセット。
const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

// Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};
const enabled = true;
const tags = {
  myCustomTag: "myCustomTagsValue",
};

async function main() {
  await client.beginCreateCertificate(certificateName, certificatePolicy, {
    enabled,
    tags,
  });
}

main();

beginCreateCertificateを同じ名前で呼び出すと、同じ証明書の新しいバージョンが作成され、最新の属性が指定されます。

証明書が完全に作成されるまでに時間がかかるため、 beginCreateCertificate ガイドラインに従って基になる長時間実行操作を追跡する poller オブジェクトを返します。 https://azure.github.io/azure-sdk/typescript_design.html#ts-lro

受信したポーラーを使用すると、 を呼び出すことで、作成された証明書を poller.getResult()取得できます。 また、証明書が作成されるまで個々のサービス呼び出しを実行するか、プロセスが完了するまで待機することで、削除が完了するまで待機することもできます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};

async function main() {
  const poller = await client.beginCreateCertificate(certificateName, certificatePolicy);

  // You can use the pending certificate immediately:
  const pendingCertificate = poller.getResult();

  // Or you can wait until the certificate finishes being signed:
  const keyVaultCertificate = await poller.pollUntilDone();
  console.log(keyVaultCertificate);
}

main();

証明書が署名されるまで待機するもう 1 つの方法は、次のように個々の呼び出しを行うことです。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");
const { delay } = require("@azure/core-util");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};

async function main() {
  const poller = await client.beginCreateCertificate(certificateName, certificatePolicy);

  while (!poller.isDone()) {
    await poller.poll();
    await delay(5000);
  }

  console.log(`The certificate ${certificateName} is fully created`);
}

main();

Key Vault証明書の取得

コンテナーから証明書を読み取り戻す最も簡単な方法は、名前で証明書を取得することです。 getCertificate では、証明書の最新バージョンと証明書のポリシーが取得されます。 必要に応じて、バージョンを指定した場合に を呼び出 getCertificateVersion して、別のバージョンの証明書を取得できます。 getCertificateVersion は証明書のポリシーを返しません。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const latestCertificate = await client.getCertificate(certificateName);
  console.log(`Latest version of the certificate ${certificateName}: `, latestCertificate);
  const specificCertificate = await client.getCertificateVersion(
    certificateName,
    latestCertificate.properties.version
  );
  console.log(
    `The certificate ${certificateName} at the version ${latestCertificate.properties.version}: `,
    specificCertificate
  );
}

main();

証明書の完全な情報の取得

Azure Key Vaultの設計では、キー、シークレット、証明書が区別されます。 Key Vault サービスの証明書機能は、キーとシークレットの機能を使用して設計されています。 Key Vault証明書の構成を評価してみましょう。

Key Vault 証明書が作成されると、アドレス指定可能なキーとシークレットも同じ名前で作成されます。 Key Vault のキーを使うとキー操作を行うことができ、Key Vault のシークレットを使うとシークレットとして証明書の値を取得できます。 Key Vault 証明書には、公開 x509 証明書メタデータも含まれます。 ソース: 証明書の構成

秘密キーがKey Vault シークレットに格納され、公開証明書が含まれていることを知っている場合は、Key Vault シークレット クライアントを使用して取得できます。

// Using the same credential object we used before,
// and the same keyVaultUrl,
// let's create a SecretClient
import { SecretClient } from "@azure/keyvault-secrets";

const secretClient = new SecretClient(keyVaultUrl, credential);

// Assuming you've already created a Key Vault certificate,
// and that certificateName contains the name of your certificate
const certificateSecret = await secretClient.getSecret(certificateName);

// Here we can find both the private key and the public certificate, in PKCS 12 format:
const PKCS12Certificate = certificateSecret.value!;

// You can write this into a file:
fs.writeFileSync("myCertificate.p12", PKCS12Certificate);

既定では、証明書のコンテンツ タイプは PKCS 12 であることに注意してください。 証明書のコンテンツ タイプを指定すると、PEM 形式で取得できます。 PEM 証明書を作成する方法を示す前に、まず PKCS 12 証明書から PEM 秘密鍵を取得する方法について説明します。

を使用すると openssl、次のコマンドを使用して、PEM 形式でパブリック証明書を取得できます。

openssl pkcs12 -in myCertificate.p12 -out myCertificate.crt.pem -clcerts -nokeys

を使用 openssl して、次のように秘密キーを取得することもできます。

openssl pkcs12 -in myCertificate.p12 -out myCertificate.key.pem -nocerts -nodes

どちらの場合も、openssl は証明書の作成に使用するパスワードを求めることに注意してください。 これまでに使用したサンプル コードではパスワードが指定されていないため、各コマンドの末尾に を追加 -passin 'pass:' できます。

PEM 形式の証明書

PEM 形式の証明書を操作する場合は、証明書を作成する時点で プロパティを指定contentTypeして、PEM 形式で証明書を作成および管理するように Azure の Key Vault サービスに指示できます。

次の例では、証明書とシークレットのKey Vault クライアントを使用して、PEM 形式の証明書のパブリック部分とプライベート部分を作成および取得する方法を示します。

// Creating the certificate
const certificateName = "MyCertificate";
const createPoller = await client.beginCreateCertificate(certificateName, {
  issuerName: "Self",
  subject: "cn=MyCert",
  contentType: "application/x-pem-file", // Here you specify you want to work with PEM certificates.
});
const keyVaultCertificate = await createPoller.pollUntilDone();

// Getting the PEM formatted private key and public certificate:
const certificateSecret = await secretClient.getSecret(certificateName);
const PEMPair = certificateSecret.value!;

console.log(PEMPair);

公開証明書は、秘密キーと同じコンテンツ BLOB に含まれることに注意してください。 PEM ヘッダーを使用して、それに応じて抽出できます。

すべての証明書を一覧表示する

listPropertiesOfCertificatesでは、Key Vault内のすべての証明書が一覧表示されます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

async function main() {
  for await (let certificateProperties of client.listPropertiesOfCertificates()) {
    console.log("Certificate properties: ", certificateProperties);
  }
}

main();

証明書の更新

証明書属性は、次のように を使用して既存の証明書バージョンに updateCertificate更新できます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const result = await client.getCertificate(certificateName);
  await client.updateCertificateProperties(certificateName, result.properties.version, {
    enabled: false,
    tags: {
      myCustomTag: "myCustomTagsValue",
    },
  });
}

main();

証明書のポリシーは、次のように を使用して updateCertificatePolicy個別に更新することもできます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const result = client.getCertificate(certificateName);
  // Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
  await client.updateCertificatePolicy(certificateName, {
    issuerName: "Self",
    subject: "cn=MyCert",
  });
}

main();

証明書の削除

メソッドは beginDeleteCertificate 、削除のために証明書を設定します。 このプロセスは、必要なリソースが利用可能になるとすぐにバックグラウンドで行われます。

Key Vaultに対して論理的な削除が有効になっている場合、この操作では、証明書に削除された証明書としてのみラベルが付けられます。 削除された証明書は更新できません。 読み取り、回復、または消去のみが可能です。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const poller = await client.beginDeleteCertificate(certificateName);

  // You can use the deleted certificate immediately:
  const deletedCertificate = poller.getResult();

  // The certificate is being deleted. Only wait for it if you want to restore it or purge it.
  await poller.pollUntilDone();

  // You can also get the deleted certificate this way:
  await client.getDeletedCertificate(certificateName);

  // Deleted certificates can also be recovered or purged.

  // recoverDeletedCertificate returns a poller, just like beginDeleteCertificate.
  // const recoverPoller = await client.beginRecoverDeletedCertificate(certificateName);
  // await recoverPoller.pollUntilDone();

  // If a certificate is done and the Key Vault has soft-delete enabled, the certificate can be purged with:
  await client.purgeDeletedCertificate(certificateName);
}

main();

証明書の削除はすぐには行われませんので、削除された beginDeleteCertificate 証明書を読み取り、回復、または消去できるようになる前に、メソッドが呼び出されてからしばらく時間が必要です。

証明書の一覧の反復処理

CertificateClient を使用すると、Certificate Vault 内のすべての証明書、および削除されたすべての証明書と特定の証明書のバージョンを取得して反復処理できます。 次の API メソッドを使用できます。

  • listPropertiesOfCertificates は、削除されていないすべての証明書を最新バージョンでのみ、その名前で一覧表示します。
  • listDeletedCertificates は、削除されたすべての証明書を最新バージョンでのみ、その名前で一覧表示します。
  • listPropertiesOfCertificateVersions は、証明書名に基づいて証明書のすべてのバージョンを一覧表示します。

次のように使用できます。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  for await (let certificateProperties of client.listPropertiesOfCertificates()) {
    console.log("Certificate properties: ", certificateProperties);
  }
  for await (let deletedCertificate of client.listDeletedCertificates()) {
    console.log("Deleted certificate: ", deletedCertificate);
  }
  for await (let certificateProperties of client.listPropertiesOfCertificateVersions(
    certificateName
  )) {
    console.log("Certificate properties: ", certificateProperties);
  }
}

main();

これらのメソッドはすべて、 使用可能なすべての結果を 一度に返します。 ページで取得するには、使用する API メソッドを呼び出した直後に、次のように を追加 .byPage() します。

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  for await (let page of client.listPropertiesOfCertificates().byPage()) {
    for (let certificateProperties of page) {
      console.log("Certificate properties: ", certificateProperties);
    }
  }
  for await (let page of client.listDeletedCertificates().byPage()) {
    for (let deletedCertificate of page) {
      console.log("Deleted certificate: ", deletedCertificate);
    }
  }
  for await (let page of client.listPropertiesOfCertificateVersions(certificateName).byPage()) {
    for (let certificateProperties of page) {
      console.log("Properties of certificate: ", certificateProperties);
    }
  }
}

main();

トラブルシューティング

ログの記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、環境変数 AZURE_LOG_LEVELinfo に設定します。 または、@azure/loggersetLogLevel を呼び出して、実行時にログ記録を有効にすることもできます。

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

さまざまな障害シナリオを診断する方法の詳細については、 トラブルシューティング ガイド を参照してください。

次の手順

その他のコード サンプルについては、次のリンクを参照してください。

共同作成

このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。

インプレッション数