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

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

Note

此快速入门使用 v3.0.4 版本的 Microsoft.Azure.KeyVault 客户端库。This quickstart uses the v3.0.4 version of the Microsoft.Azure.KeyVault client library. 若要使用 Key Vault 客户端库的最新版本,请参阅适用于 .NET 的 Azure Key Vault 客户端库 (SDK v4)To use the most up-to-date version of the Key Vault client library, see Azure Key Vault client library for .NET (SDK v4).

Azure 密钥保管库可帮助保护云应用程序和服务使用的加密密钥和机密。Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. 使用适用于 .NET 的 Key Vault 客户端库可以:Use the Key Vault client library for .NET 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 参考文档 | 库源代码 | 包 (NuGet)API reference documentation | Library source code | Package (NuGet)

Note

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

先决条件Prerequisites

本快速入门假定你正在 Windows 终端(例如 PowerShell CoreWindows PowerShell)中运行 dotnetAzure CLI 和 Windows 命令。This quickstart assumes you are running dotnet, Azure CLI, and Windows commands in a Windows terminal (such as PowerShell Core, Windows PowerShell.

设置Setting up

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

在控制台窗口中,使用 dotnet new 命令新建名为 akv-dotnet 的 .NET 控制台应用。In a console window, use the dotnet new command to create a new .NET console app with the name akv-dotnet.

dotnet new console -n akvdotnet

将目录更改为新创建的应用文件夹。Change your directory to the newly created app folder. 可使用以下代码生成应用程序:You can build the application with:

dotnet build

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

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

安装包Install the package

在控制台窗口中,安装适用于 .NET 的 Azure Key Vault 客户端库:From the console window, install the Azure Key Vault client library for .NET:

dotnet add package Microsoft.Azure.KeyVault

本快速入门还需要安装以下包:For this quickstart, you will need to install the following packages as well:

dotnet add package System.Threading.Tasks
dotnet add package Microsoft.IdentityModel.Clients.ActiveDirectory
dotnet add package Microsoft.Azure.Management.ResourceManager.Fluent

创建资源组和 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.

Important

每个密钥保管库必须具有唯一的名称。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

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

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

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

az ad sp create-for-rbac -n "http://&lt;my-unique-service-principle-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 Authenticate to your key vault 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

对象模型Object model

使用适用于 .NET 的 Azure Key Vault 客户端库可以管理密钥和相关的资产(例如证书和机密)。The Azure Key Vault client library for .NET allows you to manage keys and related assets such as certificates and secrets. 以下代码示例演示如何设置机密和检索机密。The code samples below will show you how to set a secret and retrieve 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/akvdotnet.

代码示例Code examples

添加指令Add directives

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

using System;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;

对 Key Vault 进行身份验证Authenticate to your key vault

本 .NET 快速入门依赖于使用环境变量来存储不应放入代码中的凭据。This .NET quickstart relies on environment variables to store credentials that should not be put in code.

在生成和运行应用之前,请使用 setx 命令将 akvClientIdakvClientSecretakvTenantIdakvSubscriptionId 环境变量设置为上面记下的值。Before you build and run your app, use the setx command to set the akvClientId, akvClientSecret, akvTenantId, and akvSubscriptionId environment variables to the values you noted above.

WindowsWindows

setx akvClientId "<your-clientID>"
setx akvClientSecret "<your-clientSecret>"

LinuxLinux

export akvClientId = "<your-clientID>"
export akvClientSecret = "<your-clientSecret>"

MacOSMacOS

export akvClientId = "<your-clientID>"
export akvClientSecret = "<your-clientSecret>"

将这些环境变量分配到代码中的字符串,然后通过将这些字符串传递给 KeyVaultClient 类,来对应用程序进行身份验证:Assign these environment variables to strings in your code, and then authenticate your application by passing them to the KeyVaultClient class:

string clientId = Environment.GetEnvironmentVariable("akvClientId");
string clientSecret = Environment.GetEnvironmentVariable("akvClientSecret");

KeyVaultClient kvClient = new KeyVaultClient(async (authority, resource, scope) =>
{
    var adCredential = new ClientCredential(clientId, clientSecret);
    var authenticationContext = new AuthenticationContext(authority, null);
    return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
});

保存机密Save a secret

对应用程序进行身份验证后,可以使用 SetSecretAsync 方法将机密放入 Key Vault。这需要使用 Key Vault 的 URL,其格式为 https://<your-unique-keyvault-name>.vault.azure.cn/secrets/Now that your application is authenticated, you can put a secret into your keyvault using the SetSecretAsync method This requires the URL of your key vault, which is in the form https://<your-unique-keyvault-name>.vault.azure.cn/secrets/. 还需要使用机密的名称 - 我们使用了“mySecret”。It also requires a name for the secret -- we're using "mySecret".

await kvClient.SetSecretAsync($"{kvURL}", 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

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

var keyvaultSecret = await kvClient.GetSecretAsync($"{kvURL}", secretName).ConfigureAwait(false);

机密现已保存为 keyvaultSecret.Value;Your secret is now saved as keyvaultSecret.Value;.

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

后续步骤Next steps

在本快速入门中,你创建了一个 Key Vault、存储了一个机密,然后检索了该机密。In this quickstart you created a key vault, stored a secret, and retrieved that secret. 请查看 GitHub 中的整个控制台应用See the entire console app in GitHub.

若要详细了解 Key Vault 以及如何将其与应用程序集成,请继续阅读以下文章。To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.