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

适用于 JavaScript 的 Azure Key Vault 证书客户端库入门。Get started with the Azure Key Vault certificate client library for JavaScript. Azure Key Vault 是一项云服务,它为证书提供了安全的存储。Azure Key Vault is a cloud service that provides a secure store for certificates. 可以安全地存储密钥、密码、证书和其他机密。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 certificates 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 certificates, see:

先决条件Prerequisites

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

登录 AzureSign in to Azure

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

    az cloud set -n AzureChinaCloud
    az login
    

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

    否则,请在 https://login.partner.microsoftonline.cn/common/oauth2/deviceauth 处打开浏览器页,然后输入终端中显示的授权代码。Otherwise, open a browser page at https://login.partner.microsoftonline.cn/common/oauth2/deviceauth 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 certificates library for Node.js.

npm install @azure/keyvault-certificates

安装 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 certificate permissions to your user account

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

代码示例Code examples

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

设置应用框架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 { CertificateClient } = require("@azure/keyvault-certificates");

进行身份验证并创建客户端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.

在下面的示例中,密钥保管库的名称将扩展为密钥保管库 URI,格式为“https://<your-key-vault-name>.vault.azure.cn”。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.cn". 此示例使用 Azure 标识库“DefaultAzureCredential()”类,该类允许在具有不同选项的不同环境中使用相同代码提供标识。This example is using 'DefaultAzureCredential()' class from Azure Identity Library, which allows to use the same code across different environments with different options to provide identity. 有关向 Key Vault 进行身份验证的详细信息,请参阅开发人员指南Fore 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.cn";

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

保存证书Save a certificate

现在,应用程序已进行身份验证,可以使用 beginCreateCertificate method 方法将证书放入 keyvault 中,这需要证书的名称和具有证书策略属性的证书策略证书策略Now that your application is authenticated, you can put a certificate into your keyvault using the beginCreateCertificate method This requires a name for the certificate and the certificate policycertificate policy with certificate policy properties

const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert"
};
const createPoller = await client.beginCreateCertificate(certificateName, certificatePolicy);
const certificate = await poller.pollUntilDone();

备注

如果证书名已存在,则上面的代码将创建该证书的新版本。If certificate name exists, above code will create new version of that certificate.

检索证书Retrieve a certificate

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

const retrievedCertificate = await client.getCertificate(certificateName);

删除证书Delete a certificate

最后,让我们使用 [beginDeleteCertificate]https://docs.microsoft.com/javascript/api/@azure/keyvault-certificates/certificateclient?#beginDeleteCertificate_string__BeginDeleteCertificateOptions_) 和 purgeDeletedCertificate 方法从密钥保管库中删除并清除证书。Finally, let's delete and purge the certificate from your key vault with the [beginDeleteCertificate]https://docs.microsoft.com/javascript/api/@azure/keyvault-certificates/certificateclient?#beginDeleteCertificate_string__BeginDeleteCertificateOptions_) and purgeDeletedCertificate methods.

const deletePoller = await client.beginDeleteCertificate(certificateName);
await deletePoller.pollUntilDone();
await client.purgeDeletedCertificate(certificateName);

示例代码Sample code

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

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 string certificateName = "myCertificate";
  const keyVaultName = process.env["KEY_VAULT_NAME"];
  const KVUri = "https://" + keyVaultName + ".vault.azure.cn";

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

  console.log("Creating a certificate in " + keyVaultName + " called '" + certificateName +  "` ...");
  const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert"
  };
  const createPoller = await client.beginCreateCertificate(certificateName, certificatePolicy);
  const certificate = await poller.pollUntilDone();

  console.log("Done.");

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

  const retrievedCertificate = await client.getCertificate(certificateName);

  console.log("Your certificate version is '" + retrievedCertificate.properties.version + "'.");

  console.log("Deleting your certificate from " + keyVaultName + " ...");
  const deletePoller = await client.beginDeleteCertificate(certificateName);
  await deletePoller.pollUntilDone();
  console.log("Done.");
  
  console.log("Purging your certificate from {keyVaultName} ...");
  await client.purgeDeletedCertificate(certificateName);
  
}

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

测试和验证Test and verify

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

npm install
npm index.js

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

Creating a certificate in mykeyvault called 'myCertificate' ... done.
Retrieving your certificate from mykeyvault.
Your certificate version is '8532359bced24e4bb2525f2d2050738a'.
Deleting your certificate from mykeyvault ... done
Purging your certificate from mykeyvault ... done 

后续步骤Next steps

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