Редактиране

Споделяне чрез


Quickstart: Azure Key Vault secret client library for JavaScript

Get started with the Azure Key Vault secret client library for JavaScript. Azure Key Vault is a cloud service that provides a secure store for secrets. You can securely store keys, passwords, certificates, and other secrets. Azure key vaults may be created and managed through the Azure portal. In this quickstart, you learn how to create, retrieve, and delete secrets from an Azure key vault using the JavaScript client library.

Key Vault client library resources:

API reference documentation | Library source code | Package (npm)

For more information about Key Vault and secrets, see:

Prerequisites

Prerequisites

This quickstart assumes you are running Azure CLI.

Sign in to Azure

  1. Run the login command.

    az login
    

    If the CLI can open your default browser, it will do so and load an Azure sign-in page.

    Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.

  2. Sign in with your account credentials in the browser.

Create a resource group and key vault

  1. Use the az group create command to create a resource group:

    az group create --name myResourceGroup --location eastus
    

    You can change "eastus" to a location nearer to you, if you prefer.

  2. Use az keyvault create to create the key vault:

    az keyvault create --name <your-unique-keyvault-name> --resource-group myResourceGroup
    

    Replace <your-unique-keyvault-name> with a name that's unique across all of Azure. You typically use your personal or company name along with other numbers and identifiers.

Grant access to your key vault

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

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

Replace <upn>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Create new Node.js application

Create a Node.js application that uses your key vault.

  1. In a terminal, create a folder named key-vault-node-app and change into that folder:

    mkdir key-vault-node-app && cd key-vault-node-app
    
  2. Initialize the Node.js project:

    npm init -y
    

Install Key Vault packages

  1. Using the terminal, install the Azure Key Vault secrets client library, @azure/keyvault-secrets for Node.js.

    npm install @azure/keyvault-secrets
    
  2. Install the Azure Identity client library, @azure/identity package to authenticate to a Key Vault.

    npm install @azure/identity
    

Grant access to your key vault

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

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

Replace <upn>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Set environment variables

This application is using key vault endpoint as an environment variable called KEY_VAULT_URL.

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

Authenticate and create a client

Application requests to most Azure services must be authorized. Using the DefaultAzureCredential method provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code. DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.

In this quickstart, DefaultAzureCredential authenticates to key vault using the credentials of the local development user logged into the Azure CLI. When the application is deployed to Azure, the same DefaultAzureCredential code can automatically discover and use a managed identity that is assigned to an App Service, Virtual Machine, or other services. For more information, see Managed Identity Overview.

In this code, the endpoint of your key vault is used to create the key vault client. The endpoint format looks like https://<your-key-vault-name>.vault.azure.net but may change for sovereign clouds. For more information about authenticating to key vault, see Developer's Guide.

Code example

The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

This code uses the following Key Vault Secret classes and methods:

Set up the app framework

  • Create new text file and paste the following code into the index.js file.

    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);
    });
    

Run the sample application

  1. Run the app:

    node index.js
    
  2. The create and get methods return a full JSON object for the secret:

    {
        "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"
        }
    }
    

    The update method returns the properties name/values pairs:

    "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"
    
  • Create new text file and paste the following code into the index.ts file.

    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);
    });
    

Run the sample application

  1. Build the TypeScript app:

    tsc
    
  2. Run the app:

    node index.js
    
  3. The create and get methods return a full JSON object for the secret:

    {
        "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"
        }
    }
    

    The update method returns the properties name/values pairs:

    "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"
    

Integrating with App Configuration

The Azure SDK provides a helper method, parseKeyVaultSecretIdentifier, to parse the given Key Vault Secret ID. This is necessary if you use App Configuration references to Key Vault. App Config stores the Key Vault Secret ID. You need the parseKeyVaultSecretIdentifier method to parse that ID to get the secret name. Once you have the secret name, you can get the current secret value using code from this quickstart.

Next steps

In this quickstart, you created a key vault, stored a secret, and retrieved that secret. To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.