快速入门:适用于 .NET 的 Azure Key Vault 证书客户端库 (SDK v4)Quickstart: Azure Key Vault certificate client library for .NET (SDK v4)

适用于 .NET 的 Azure Key Vault 证书客户端库入门。Get started with the Azure Key Vault certificate client library for .NET. 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. 本快速入门介绍如何使用 .NET 客户端库在 Azure 密钥保管库中创建、检索和删除证书In this quickstart, you learn how to create, retrieve, and delete certificates from an Azure key vault using the .NET client library

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

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

有关 Key Vault 和证书的详细信息,请参阅:For more information about Key Vault and certificates, see:

先决条件Prerequisites

本快速入门使用 dotnet 和 Azure CLIThis quickstart is using dotnet and Azure CLI

设置Setup

本快速入门结合使用 Azure Identity 库和 Azure CLI,向 Azure 服务验证用户身份。This quickstart is using Azure Identity library with Azure CLI to authenticate user to Azure Services. 开发人员还可以使用 Visual Studio 或 Visual Studio Code 来验证其调用。有关详细信息,请参阅使用 Azure Identity 客户端库对客户端进行身份验证Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.

登录 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.

创建新的 .NET 控制台应用Create new .NET console app

  1. 在命令外壳中,运行以下命令以创建名为 key-vault-console-app 的项目:In a command shell, run the following command to create a project named key-vault-console-app:

    dotnet new console --name key-vault-console-app
    
  2. 切换到新创建的 key-vault-console-app 目录,然后运行以下命令来生成项目:Change to the newly created key-vault-console-app directory, and run the following command to build the project:

    dotnet build
    

    生成输出不应包含警告或错误。The build output should contain no warnings or errors.

    Build succeeded.
     0 Warning(s)
     0 Error(s)
    

安装包Install the packages

在命令外壳中,安装适用于 .NET 的 Azure Key Vault 证书客户端库:From the command shell, install the Azure Key Vault certificate client library for .NET:

dotnet add package Azure.Security.KeyVault.Certificates

对于本快速入门,还需要安装适用于 Azure Identity 的 Azure SDK 客户端库:For this quickstart, you'll also need to install the Azure SDK client library for Azure Identity:

dotnet add package Azure.Identity

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

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

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

设置环境变量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>

对象模型Object model

使用适用于 .NET 的 Azure Key Vault 证书客户端库管理证书。The Azure Key Vault certificate client library for .NET allows you to manage certificates. 代码示例部分介绍了如何创建客户端,以及如何设置、检索和删除证书。The Code examples section shows how to create a client, set a certificate, retrieve a certificate, and delete a certificate.

代码示例Code examples

添加指令Add directives

在 Program.cs 的顶部添加以下指令:Add the following directives to the top of Program.cs:

using System;
using Azure.Identity;
using Azure.Security.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. 有关向密钥保管库进行身份验证的详细信息,请参阅开发人员指南For more information about authenticating to key vault, see Developer's Guide.

string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.cn";

var client = new CertificateClient(new Uri(kvUri), new DefaultAzureCredential());

保存证书Save a certificate

在此示例中,为简单起见,可以将自签名证书与默认颁发策略一起使用。In this example, for simplicity you can use self-signed certificate with default issuance policy. 对于此任务,请使用 StartCreateCertificateAsync 方法。For this task, use the StartCreateCertificateAsync method. 该方法的参数接受证书名和证书策略证书策略The method's parameters accepts a certificate name and the certificate policycertificate policy.

var operation = await client.StartCreateCertificateAsync("myCertificate", CertificatePolicy.Default);
var certificate = await operation.WaitForCompletionAsync();

备注

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

检索证书Retrieve a certificate

现在,可以使用 GetCertificateAsync 方法检索以前创建的证书。You can now retrieve the previously created certificate with the GetCertificateAsync method.

var certificate = await client.GetCertificateAsync("myCertificate");

删除证书Delete a certificate

最后,让我们使用 StartDeleteCertificateAsyncPurgeDeletedCertificateAsync 方法从密钥保管库中删除并清除证书。Finally, let's delete and purge the certificate from your key vault with the StartDeleteCertificateAsync and PurgeDeletedCertificateAsync methods.

var operation = await client.StartDeleteCertificateAsync("MyCertificate");

// You only need to wait for completion if you want to purge or recover the certificate.
await operation.WaitForCompletionAsync();

var certificate = operation.Value;
await client.PurgeDeletedCertificateAsync(certificate.Name);

示例代码Sample code

通过完成以下步骤,将 .NET Core 控制台应用修改为与 Key Vault 交互:Modify the .NET Core console app to interact with the Key Vault by completing the following steps:

  1. 将 Program.cs 中的代码替换为以下代码:Replace the code in Program.cs with the following code:

    using System;
    using System.Threading.Tasks;
    using Azure.Identity;
    using Azure.Security.KeyVault.Certificates;
    
    namespace key_vault_console_app
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                const string certificateName = "myCertificate";
                var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
                var kvUri = $"https://{keyVaultName}.vault.azure.cn";
    
                var client = new CertificateClient(new Uri(kvUri), new DefaultAzureCredential());
    
                Console.Write($"Creating a certificate in {keyVaultName} called '{certificateName}' ...");
                CertificateOperation operation = await client.StartCreateCertificateAsync(certificateName, CertificatePolicy.Default);
                await operation.WaitForCompletionAsync();
                Console.WriteLine(" done.");
    
                Console.WriteLine($"Retrieving your certificate from {keyVaultName}.");
                var certificate = await client.GetCertificateAsync(certificateName);
                Console.WriteLine($"Your certificate value is '{certificate.Value.Properties.Version}'.");
    
                Console.Write($"Deleting your certificate from {keyVaultName} ...");
                DeleteCertificateOperation deleteOperation = await client.StartDeleteCertificateAsync(certificateName);
                // You only need to wait for completion if you want to purge or recover the certificate.
                await deleteOperation.WaitForCompletionAsync();
                Console.WriteLine(" done.");
    
                Console.Write($"Purging your certificate from {keyVaultName} ...");
                await client.PurgeDeletedCertificateAsync(certificateName);
                Console.WriteLine(" done.");
            }
        }
    }
    

测试和验证Test and verify

  1. 执行以下命令以生成项目Execute the following command to build the project

    dotnet build
    
  2. 执行以下命令来运行应用。Execute the following command to run the app.

    dotnet run
    
  3. 出现提示时,输入一个密码值。When prompted, enter a secret value. 例如,mySecretPassword。For example, mySecretPassword.

    随即显示以下输出的变体: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 jl-kv ... done
    

清理资源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.

删除 Key VaultDelete a Key Vault

az keyvault delete --name <your-unique-keyvault-name>
Remove-AzKeyVault -VaultName <your-unique-keyvault-name>

清除 Key VaultPurge a Key Vault

az keyvault purge --location chinanorth --name <your-unique-keyvault-name>
Remove-AzKeyVault -VaultName <your-unique-keyvault-name> -InRemovedState -Location chinanorth

删除资源组Delete a resource group

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

后续步骤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 apps, see the following articles: