快速入门:适用于 Node.js 的 Azure Key Vault 客户端库 (v4)Quickstart: Azure Key Vault client library for Node.js (v4)

本快速入门将介绍适用于 Node.js 的 Azure Key Vault 客户端库。Get started with the Azure Key Vault client library for Node.js. 请遵循以下步骤安装包并试用基本任务的示例代码。Follow the steps below to install the package and try out example code for basic tasks.

Azure 密钥保管库可帮助保护云应用程序和服务使用的加密密钥和机密。Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. 使用适用于 Node.js 的 Key Vault 客户端库可以:Use the Key Vault client library for Node.js to:

  • 提高安全性以及控制密钥和密码。Increase security and control over keys and passwords.
  • 在几分钟内创建并导入加密密钥。Create and import encryption keys in minutes.
  • 通过云扩展和全局冗余减少延迟。Reduce latency with cloud scale and global redundancy.
  • 简化和自动化与 TLS/SSL 证书相关的任务。Simplify and automate tasks for TLS/SSL certificates.

API 参考文档 | 库源代码 | 包 (npm)API reference documentation | Library source code | Package (npm)

先决条件Prerequisites

本快速入门假设你在 Linux 终端窗口中运行 Azure CLIThis quickstart assumes you are running Azure CLI in a Linux terminal window.

设置Setting up

安装包Install the package

在控制台窗口中,安装适用于 Node.js 的 Azure Key Vault 机密库。From the console window, install the Azure Key Vault secrets library for Node.js.

npm install @azure/keyvault-secrets

本快速入门还需要安装 azure.identity 包:For this quickstart, you will need to install the azure.identity package as well:

npm install @azure/identity

创建资源组和 Key VaultCreate a resource group and key vault

本快速入门使用预先创建的 Azure Key Vault。This quickstart uses a pre-created Azure key vault. 可以遵循 Azure CLI 快速入门Azure PowerShell 快速入门Azure 门户快速入门中的步骤创建 Key Vault。You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart. 或者,只需运行以下 Azure CLI 命令。Alternatively, you can simply run the Azure CLI commands below.

重要

每个密钥保管库必须具有唯一的名称。Each key vault must have a unique name. 在以下示例中,将 替换为密钥保管库的名称。Replace with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "ChinaEast"

az keyvault create --name <your-unique-keyvault-name> -g "myResourceGroup"

创建服务主体Create a service principal

对基于云的应用程序进行身份验证的最简单方法是使用托管标识;有关详细信息,请参阅使用应用服务托管标识访问 Azure Key VaultThe simplest way to authenticate an cloud-based application is with a managed identity; see Use an App Service managed identity to access Azure Key Vault for details.

不过,为了简单起见,本快速入门创建了一个需要使用服务主体和访问控制策略的桌面应用程序。For the sake of simplicity however, this quickstart creates a desktop application, which requires the use of a service principal and an access control policy. 服务主体要求使用格式为“http://<my-unique-service-principal-name>”的唯一名称。Your service principal requires a unique name in the format "http://<my-unique-service-principal-name>".

使用 Azure CLI az ad sp create-for-rbac 命令创建服务主体:Create a service principal using the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://&lt;my-unique-service-principal-name&gt;" --sdk-auth

此操作将返回一系列键/值对。This operation will return a series of key / value pairs.

{
  "clientId": "7da18cae-779c-41fc-992e-0527854c6583",
  "clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
  "subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
  "tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
  "activeDirectoryEndpointUrl": "https://login.chinacloudapi.cn",
  "resourceManagerEndpointUrl": "https://management.chinacloudapi.cn/",
  "sqlManagementEndpointUrl": "https://management.core.chinacloudapi.cn:8443/",
  "galleryEndpointUrl": "https://gallery.chinacloudapi.cn/",
  "managementEndpointUrl": "https://management.core.chinacloudapi.cn/"
}

请记下 clientId 和 clientSecret,因为在下面的设置环境变量步骤中将要用到。Take note of the clientId and clientSecret, as we will use them in the Set environmental variable step below.

为服务主体授予对 Key Vault 的访问权限Give the service principal access to your key vault

通过将 clientId 传递给 az keyvault set-policy 命令,为密钥保管库创建授予服务主体权限的访问策略。Create an access policy for your key vault that grants permission to your service principal by passing the clientId to the az keyvault set-policy command. 授予服务主体对密钥和机密的 get、list 和 set 权限。Give the service principal get, list, and set permissions for both keys and secrets.

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --secret-permissions delete get list set --key-permissions create decrypt delete encrypt get list unwrapKey wrapKey

设置环境变量Set environmental variables

应用程序中的 DefaultAzureCredential 方法依赖于三个环境变量:AZURE_CLIENT_IDAZURE_CLIENT_SECRETAZURE_TENANT_IDThe DefaultAzureCredential method in our application relies on three environmental variables: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. 请使用 export VARNAME=VALUE 格式将这些变量设置为在上述创建服务主体步骤中记下的 clientId、clientSecret 和 tenantId 值。Set these variables to the clientId, clientSecret, and tenantId values you noted in the Create a service principal step using the export VARNAME=VALUE format. (这只为当前 shell 和从 shell 创建的进程设置变量;若要将这些变量永久添加到环境中,请编辑 /etc/environment 文件。)(This only sets the variables for your current shell and processes created from the shell; to permanently add these variables to your environment, edit your /etc/environment file.)

还需要将密钥保管库名称另存为名为 KEY_VAULT_NAME 的环境变量。You will also need to save your key vault name as an environment variable called KEY_VAULT_NAME.

export AZURE_CLIENT_ID=<your-clientID>

export AZURE_CLIENT_SECRET=<your-clientSecret>

export AZURE_TENANT_ID=<your-tenantId>

export KEY_VAULT_NAME=<your-key-vault-name>

对象模型Object model

使用适用于 Node.js 的 Azure Key Vault 客户端库可以管理密钥和相关的资产(例如证书和机密)。The Azure Key Vault client library for Node.js allows you to manage keys and related assets such as certificates and secrets. 以下代码示例演示如何创建客户端以及设置、检索和删除机密。The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

https://github.com/Azure-Samples/key-vault-dotnet-core-quickstart/tree/master/akvdotnet 中提供了整个控制台应用。The entire console app is available at https://github.com/Azure-Samples/key-vault-dotnet-core-quickstart/tree/master/key-vault-console-app.

代码示例Code examples

添加指令Add directives

将以下指令添加到代码的顶部:Add the following directives to the top of your code:

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

进行身份验证并创建客户端Authenticate and create a client

向密钥保管库进行身份验证和创建密钥保管库客户端依赖于上面设置环境变量步骤中的环境变量以及 SecretClient 构造函数Authenticating to your key vault and creating a key vault client depends on the environmental variables from the Set environmental variables step above, and the SecretClient constructor.

密钥保管库的名称将扩展为密钥保管库 URI,格式为 https://<your-key-vault-name>.vault.azure.cnThe name of your key vault is expanded to the key vault URI, in the format https://<your-key-vault-name>.vault.azure.cn.

const keyVaultName = process.env["KEY_VAULT_NAME"];
const KVUri = "https://" + keyVaultName + ".vault.azure.cn";
const credentialOption = new DefaultAzureCredentialOptions();
credentialOption.AuthorityHost = new Uri("https://login.partner.microsoftonline.cn");


const credential = new DefaultAzureCredential(credentialOption);
const client = new SecretClient(KVUri, credential);

保存机密Save a secret

应用程序通过身份验证后,你可以使用 client.setSecret 方法将机密放入密钥保管库。此操作需要使用机密的名称,本示例中使用“mySecret”。Now that your application is authenticated, you can put a secret into your keyvault using the client.setSecret method This requires a name for the secret -- we're using "mySecret" in this sample.

await client.setSecret(secretName, secretValue);

可以使用 az keyvault secret show 命令来验证是否设置了机密:You can verify that the secret has been set with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret

检索机密Retrieve a secret

现在,可以使用 client.getSecret 方法检索以前设置的值。You can now retrieve the previously set value with the client.getSecret method.

const retrievedSecret = await client.getSecret(secretName);

机密现已保存为 retrievedSecret.valueYour secret is now saved as retrievedSecret.value.

删除机密Delete a secret

最后,使用 client.beginDeleteSecret 方法从密钥保管库中删除机密。Finally, let's delete the secret from your key vault with the client.beginDeleteSecret method.

await client.beginDeleteSecret(secretName)

可以使用 az keyvault secret show 命令来验证是否已删除机密:You can verify that the secret is gone with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret

清理资源Clean up resources

可以使用 Azure CLI 或 Azure PowerShell 来删除不再需要的 Key Vault 和相应的资源组。When no longer needed, you can use the Azure CLI or Azure PowerShell to remove your key vault and the corresponding resource group.

az group delete -g "myResourceGroup"
Remove-AzResourceGroup -Name "myResourceGroup"

代码示例Sample code

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

const readline = require('readline');

function askQuestion(query) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    return new Promise(resolve => rl.question(query, ans => {
        rl.close();
        resolve(ans);
    }))
}

async function main() {

  const keyVaultName = process.env["KEY_VAULT_NAME"];
  const KVUri = "https://" + keyVaultName + ".vault.azure.cn";
  const credentialOption = new DefaultAzureCredentialOptions();
  credentialOption.AuthorityHost = new Uri("https://login.partner.microsoftonline.cn");

  const credential = new DefaultAzureCredential(credentialOption);
  const client = new SecretClient(KVUri, credential);

  const secretName = "mySecret";
  var secretValue = await askQuestion("Input the value of your secret > ");

  console.log("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "` ...");
  await client.setSecret(secretName, secretValue);

  console.log("Done.");

  console.log("Forgetting your secret.");
  secretValue = "";
  console.log("Your secret is '" + secretValue + "'.");

  console.log("Retrieving your secret from " + keyVaultName + ".");

  const retrievedSecret = await client.getSecret(secretName);

  console.log("Your secret is '" + retrievedSecret.value + "'.");
  console.log("Deleting your secret from " + keyVaultName + " ...");

  await client.beginDeleteSecret(secretName);

  console.log("Done.");

}

main()

后续步骤Next steps

在本快速入门中,你创建了一个 Key Vault、存储了一个机密,然后检索了该机密。In this quickstart you created a key vault, stored a secret, and retrieved that secret. 若要详细了解 Key Vault 以及如何将其与应用程序集成,请继续阅读以下文章。To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.