次の方法で共有


クイックスタート: JavaScript 用 Azure Key Vault シークレット クライアント ライブラリ

JavaScript 用 Azure Key Vault シークレットクライアント ライブラリを使ってみます。 Azure Key Vault は、シークレットのセキュリティで保護されたストアを提供するクラウド サービスです。 キー、パスワード、証明書、およびその他のシークレットを安全に保管することができます。 Azure Key Vault は、Azure Portal を使用して作成および管理できます。 このクイックスタートでは、JavaScript クライアント ライブラリを使用して Azure キー コンテナーにシークレットを作成し、それを取得および削除する方法について説明します。

Key Vault クライアント ライブラリのリソースは、次のとおりです。

API リファレンスのドキュメント | ライブラリのソース コード | パッケージ (npm)

Key Vault とシークレットの詳細については、以下を参照してください。

前提条件

前提条件

このクイックスタートでは、Azure CLI を実行していることを前提としています。

Azure へのサインイン

  1. login コマンドを実行します。

    az login
    

    CLI で既定のブラウザーを開くことができる場合、開いたブラウザに Azure サインイン ページが読み込まれます。

    それ以外の場合は、 https://aka.ms/devicelogin でブラウザー ページを開き、ターミナルに表示されている認証コードを入力します。

  2. ブラウザーでアカウントの資格情報を使用してサインインします。

新しい Node.js アプリケーションを作成する

キー コンテナーを使用する Node.js アプリケーションを作成します。

  1. ターミナルで、key-vault-node-app という名前のフォルダーを作成し、そのフォルダーに移動します。

    mkdir key-vault-node-app && cd key-vault-node-app
    
  2. Node.js プロジェクトを初期化します。

    npm init -y
    

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

  1. ターミナルを使用して、Node.js 用の Azure Key Vault シークレット クライアント ライブラリ @azure/keyvault-secrets をインストールします。

    npm install @azure/keyvault-secrets
    
  2. Key Vault の認証を行うために、Azure ID クライアント ライブラリ @azure/identity パッケージをインストールします。

    npm install @azure/identity
    

キー コンテナーへのアクセス許可を付与する

ロールベースのアクセス制御 (RBAC) を使用してキー コンテナーへのアクセス許可をアプリケーションに付与するには、Azure CLI コマンド az role assignment create を使用してロールを割り当てます。

az role assignment create --role "Key Vault Secrets User" --assignee "<app-id>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

<app-id><subscription-id><resource-group-name><your-unique-keyvault-name> を実際の値に置き換えます。 <app-id> は、Microsoft Entra 内に登録されたアプリケーションの、アプリケーション (クライアント) ID です。

環境変数の設定

このアプリケーションでは、KEY_VAULT_URL という環境変数として、キー コンテナー エンドポイントを使います。

set KEY_VAULT_URL=<your-key-vault-endpoint>

クライアントの認証と作成

ほとんどの Azure サービスに対するアプリケーション要求は、認可される必要があります。 Azure ID クライアント ライブラリによって提供される DefaultAzureCredential メソッドを使うことは、コード内の Azure サービスへのパスワードレス接続を実装するための推奨される方法です。 DefaultAzureCredential は複数の認証方法をサポートしており、実行時に使用する方法が決定されます。 このアプローチを採用すると、環境固有のコードを実装することなく、異なる環境 (ローカルと運用環境) で異なる認証方法をアプリに使用できます。

このクイックスタートでは、DefaultAzureCredential は Azure CLI にログインしたローカル開発ユーザーの資格情報を使って、キー コンテナーに対して認証されます。 アプリケーションが Azure にデプロイされると、同じDefaultAzureCredential コードで、App Service、仮想マシン、またはその他のサービスに割り当てられているマネージド ID を自動的に検出して使用できます。 詳細については、マネージド ID の概要に関するページを参照してください。

このコードでは、キー コンテナーのエンドポイントを使って、キー コンテナー クライアントを作成します。 エンドポイントの形式は https://<your-key-vault-name>.vault.azure.net のようになりますが、ソブリン クラウドでは変わる可能性があります。 キー コンテナーに対する認証の詳細については、開発者ガイドを参照してください。

コードの例

以下のコード サンプルでは、クライアントの作成、シークレットの設定、シークレットの取得、シークレットの削除を行う方法を示します。

このコードでは、次の Key Vault Secret クラスとメソッドを使用します。

アプリのフレームワークを設定する

  • 新しいテキスト ファイルを作成し、次のコードを index.js ファイルに貼り付けます。

    const { SecretClient } = require("@azure/keyvault-secrets");
    const { DefaultAzureCredential } = require("@azure/identity");
    
    async function main() {
      // If you're using MSI, DefaultAzureCredential should "just work".
      // Otherwise, DefaultAzureCredential expects the following three environment variables:
      // - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
      // - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
      // - AZURE_CLIENT_SECRET: The client secret for the registered application
      const credential = new DefaultAzureCredential();
    
      const keyVaultUrl = process.env["KEY_VAULT_URL"];
      if(!keyVaultUrl) throw new Error("KEY_VAULT_URL is empty");
    
      const client = new SecretClient(keyVaultUrl, credential);
    
      // Create a secret
      // The secret can be a string of any kind. For example,
      // a multiline text block such as an RSA private key with newline characters,
      // or a stringified JSON object, like `JSON.stringify({ mySecret: 'MySecretValue'})`.
      const uniqueString = new Date().getTime();
      const secretName = `secret${uniqueString}`;
      const result = await client.setSecret(secretName, "MySecretValue");
      console.log("result: ", result);
    
      // Read the secret we created
      const secret = await client.getSecret(secretName);
      console.log("secret: ", secret);
    
      // Update the secret with different attributes
      const updatedSecret = await client.updateSecretProperties(secretName, result.properties.version, {
        enabled: false
      });
      console.log("updated secret: ", updatedSecret);
    
      // Delete the secret immediately without ability to restore or purge.
      await client.beginDeleteSecret(secretName);
    }
    
    main().catch((error) => {
      console.error("An error occurred:", error);
      process.exit(1);
    });
    

サンプル アプリケーションの実行

  1. アプリを実行します。

    node index.js
    
  2. create および get メソッドにより、シークレットの完全な JSON オブジェクトが返されます。

    {
        "value": "MySecretValue",
        "name": "secret1637692472606",
        "properties": {
            "createdOn": "2021-11-23T18:34:33.000Z",
            "updatedOn": "2021-11-23T18:34:33.000Z",
            "enabled": true,
            "recoverableDays": 90,
            "recoveryLevel": "Recoverable+Purgeable",
            "id": "https: //YOUR-KEYVAULT-ENDPOINT.vault.azure.net/secrets/secret1637692472606/YOUR-VERSION",
            "vaultUrl": "https: //YOUR-KEYVAULT-ENDPOINT.vault.azure.net",
            "version": "YOUR-VERSION",
            "name": "secret1637692472606"
        }
    }
    

    update メソッドにより、プロパティの名前と値のペアが返されます。

    "createdOn": "2021-11-23T18:34:33.000Z",
    "updatedOn": "2021-11-23T18:34:33.000Z",
    "enabled": true,
    "recoverableDays": 90,
    "recoveryLevel": "Recoverable+Purgeable",
    "id": "https: //YOUR-KEYVAULT-ENDPOINT/secrets/secret1637692472606/YOUR-VERSION",
    "vaultUrl": "https: //YOUR-KEYVAULT-ENDPOINT",
    "version": "YOUR-VERSION",
    "name": "secret1637692472606"
    
  • index.ts という名前の新しいテキスト ファイルを作成して、次のコードを貼り付けます。

    import {
      SecretClient,
      KeyVaultSecret,
      SecretProperties,
    } from "@azure/keyvault-secrets";
    import { DefaultAzureCredential } from "@azure/identity";
    import "dotenv/config";
    
    // Passwordless credential
    const credential = new DefaultAzureCredential();
    
    // Get Key Vault name from environment variables
    // such as `https://${keyVaultName}.vault.azure.net`
    const keyVaultUrl = process.env.KEY_VAULT_URL;
    if (!keyVaultUrl) throw new Error("KEY_VAULT_URL is empty");
    
    function printSecret(secret: KeyVaultSecret): void {
      const { name, value, properties } = secret;
      const { enabled, expiresOn, createdOn } = properties;
      console.log("Secret: ", { name, value, enabled, expiresOn, createdOn });
    }
    function printSecretProperties(secret: SecretProperties): void {
      const { name, enabled, expiresOn, createdOn } = secret;
      console.log("Secret: ", { name, enabled, expiresOn, createdOn });
    }
    
    async function main(): Promise<void> {
      // Create a new SecretClient
      const client = new SecretClient(keyVaultUrl, credential);
    
      // Create a unique secret name
      const uniqueString = new Date().getTime().toString();
      const secretName = `secret${uniqueString}`;
    
      // Create a secret
      const createSecretResult = await client.setSecret(
        secretName,
        "MySecretValue"
      );
      printSecret(createSecretResult);
    
      // Get the secret by name
      const getSecretResult = await client.getSecret(secretName);
      printSecret(getSecretResult);
    
      // Update properties
      const updatedSecret = await client.updateSecretProperties(
        secretName,
        getSecretResult.properties.version,
        {
          enabled: false,
        }
      );
      printSecretProperties(updatedSecret);
    
      // Delete secret (without immediate purge)
      const deletePoller = await client.beginDeleteSecret(secretName);
      await deletePoller.pollUntilDone();
    }
    
    main().catch((error) => {
      console.error("An error occurred:", error);
      process.exit(1);
    });
    

サンプル アプリケーションの実行

  1. TypeScript アプリをビルドします。

    tsc
    
  2. アプリを実行します。

    node index.js
    
  3. create および get メソッドにより、シークレットの完全な JSON オブジェクトが返されます。

    {
        "value": "MySecretValue",
        "name": "secret1637692472606",
        "properties": {
            "createdOn": "2021-11-23T18:34:33.000Z",
            "updatedOn": "2021-11-23T18:34:33.000Z",
            "enabled": true,
            "recoverableDays": 90,
            "recoveryLevel": "Recoverable+Purgeable",
            "id": "https: //YOUR-KEYVAULT-ENDPOINT.vault.azure.net/secrets/secret1637692472606/YOUR-VERSION",
            "vaultUrl": "https: //YOUR-KEYVAULT-ENDPOINT.vault.azure.net",
            "version": "YOUR-VERSION",
            "name": "secret1637692472606"
        }
    }
    

    update メソッドにより、プロパティの名前と値のペアが返されます。

    "createdOn": "2021-11-23T18:34:33.000Z",
    "updatedOn": "2021-11-23T18:34:33.000Z",
    "enabled": true,
    "recoverableDays": 90,
    "recoveryLevel": "Recoverable+Purgeable",
    "id": "https: //YOUR-KEYVAULT-ENDPOINT/secrets/secret1637692472606/YOUR-VERSION",
    "vaultUrl": "https: //YOUR-KEYVAULT-ENDPOINT",
    "version": "YOUR-VERSION",
    "name": "secret1637692472606"
    

App Configuration との統合

Azure SDK は、指定された Key Vault シークレット ID を解析するヘルパー メソッド parseKeyVaultSecretIdentifier を提供します。 これは、Key Vault への App Configuration の参照を使用する場合に必要です。 App Config には、Key Vault シークレット ID が格納されます。 シークレット名を取得するには、その ID を解析するために parseKeyVaultSecretIdentifier メソッドが必要です。 シークレット名を取得すると、このクイック スタートのコードを使用して現在のシークレット値を取得できます。

次のステップ

このクイックスタートでは、キー コンテナーを作成し、シークレットを格納して、そのシークレットを取得しました。 Key Vault およびアプリケーションとの統合方法の詳細については、引き続き以下の記事を参照してください。