您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:适用于 JavaScript 的 Azure Key Vault 机密客户端库(版本 4)Quickstart: Azure Key Vault secret client library for JavaScript (version 4)

适用于 JavaScript 的 Azure Key Vault 机密客户端库入门。Get started with the Azure Key Vault secret client library for JavaScript. Azure Key Vault 是一项云服务,它为机密提供了安全的存储。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 门户创建和管理 Azure Key Vault。Azure key vaults may be created and managed through the Azure portal. 本快速入门介绍如何使用 JavaScript 客户端库在 Azure 密钥保管库中创建、检索和删除机密In this quickstart, you learn how to create, retrieve, and delete secrets from an Azure key vault using the JavaScript client library

Key Vault 客户端库资源:Key Vault client library resources:

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

有关 Key Vault 和机密的详细信息,请参阅:For more information about Key Vault and secrets, see:

先决条件Prerequisites

本快速入门假设你运行 Azure CLIThis quickstart assumes you are running Azure CLI.

登录 AzureSign in to Azure

  1. 运行 login 命令。Run the login command.

    az login
    

    如果 CLI 可以打开默认浏览器,它将这样做并加载 Azure 登录页。If the CLI can open your default browser, it will do so and load an Azure sign-in page.

    否则,请在 https://aka.ms/devicelogin 处打开浏览器页,然后输入终端中显示的授权代码。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.

创建新的 Node.js 应用程序Create new Node.js application

接下来,创建可部署到云的 Node.js 应用程序。Next, create a Node.js application that can be deployed to the Cloud.

  1. 在命令外壳中,创建一个名为 key-vault-node-app 的文件夹:In a command shell, create a folder named key-vault-node-app:
mkdir key-vault-node-app
  1. 切换到新创建的 key-vault-node-app 目录,然后运行 init 命令以初始化节点项目:Change to the newly created key-vault-node-app directory, and run 'init' command to initialize node project:
cd key-vault-node-app
npm init -y

安装 Key Vault 包Install Key Vault packages

在控制台窗口中,安装适用于 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 包以对 Key Vault 进行身份验证Install the azure.identity package to authenticate to a Key Vault

npm install @azure/identity

设置环境变量Set environment variables

此应用程序使用 Key Vault 名称作为名为 KEY_VAULT_NAME 的环境变量。This application is using key vault name as an environment variable called KEY_VAULT_NAME.

WindowsWindows

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

Windows PowerShellWindows PowerShell

$Env:KEY_VAULT_NAME="<your-key-vault-name>"

macOS 或 LinuxmacOS or Linux

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

授予对 Key Vault 的访问权限Grant access to your key vault

针对密钥保管库创建一个访问策略,以便为用户帐户授予机密权限Create an access policy for your key vault that grants secret permissions to your user account

az keyvault set-policy --name <YourKeyVaultName> --upn user@domain.com --secret-permissions delete get list set purge

代码示例Code examples

以下代码示例演示如何创建客户端以及设置、检索和删除机密。The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

设置应用框架Set up the app framework

  1. 创建新的文本文件并将其另存为“index.js”Create new text file and save it as 'index.js'

  2. 添加所需调用以加载 Azure 和 Node.js 模块Add require calls to load Azure and Node.js modules

  3. 为程序创建结构,包括基本的异常处理Create the structure for the program, including basic exception handling

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() {
    
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

添加指令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

本快速入门使用登录用户向 Key Vault 进行身份验证,这是本地开发的首选方法。In this quickstart, logged in user is used to authenticate to key vault, which is preferred method for local development. 对于部署到 Azure 的应用程序,应将托管标识分配给应用服务或虚拟机。有关详细信息,请参阅托管标识概述For applications deployed to Azure, managed identity should be assigned to App Service or Virtual Machine, for more information, see Managed Identity Overview.

在下面的示例中,Key Vault 的名称将扩展为 Key Vault URI,格式为“https://<your-key-vault-name>.vault.azure.net”。In below example, the name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.net". 此示例使用 Azure 标识库中的“DefaultAzureCredential()”类。利用该类,我们可以在具有不同选项的不同环境中使用相同的代码来提供标识。This example is using the 'DefaultAzureCredential()' class from Azure Identity Library, which allows us to use the same code across different environments with different options to provide identity. 有关向密钥保管库进行身份验证的详细信息,请参阅开发人员指南For more information about authenticating to key vault, see Developer's Guide.

将以下代码添加到“main()”函数Add the following code to 'main()' function

const keyVaultName = process.env["KEY_VAULT_NAME"];
const KVUri = "https://" + keyVaultName + ".vault.azure.net";

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

保存机密Save a secret

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

await client.setSecret(secretName, secretValue);

检索机密Retrieve a secret

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

const retrievedSecret = await client.getSecret(secretName);

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

删除机密Delete a secret

最后,让我们使用 beginDeleteSecretpurgeDeletedSecret 方法从密钥保管库中删除并清除机密。Finally, let's delete and purge the secret from your key vault with the beginDeleteSecret and purgeDeletedSecret methods.

const deletePoller = await client.beginDeleteSecret(secretName);
await deletePoller.pollUntilDone();
await client.purgeDeletedSecret(secretName);

示例代码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.net";

  const credential = new DefaultAzureCredential();
  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 + " ...");
  const deletePoller = await client.beginDeleteSecret(secretName);
  await deletePoller.pollUntilDone();
  console.log("Done.");
  
  console.log("Purging your secret from {keyVaultName} ...");
  await client.purgeDeletedSecret(secretName);
  
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

测试和验证Test and verify

  1. 执行以下命令来运行应用。Execute the following commands to run the app.

    npm install
    node index.js
    
  2. 出现提示时,输入一个密码值。When prompted, enter a secret value. 例如,mySecretPassword。For example, mySecretPassword.

    随即显示以下输出的变体:A variation of the following output appears:

    Input the value of your secret > mySecretPassword
    Creating a secret in <your-unique-keyvault-name> called 'mySecret' with the value 'mySecretPassword' ... done.
    Forgetting your secret.
    Your secret is ''.
    Retrieving your secret from <your-unique-keyvault-name>.
    Your secret is 'mySecretPassword'.
    Deleting your secret from <your-unique-keyvault-name> ... done.  
    Purging your secret from <your-unique-keyvault-name> ... done.   
    

后续步骤Next steps

在本快速入门中,你创建了一个密钥保管库、存储了一个机密,然后检索了该机密。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.