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

适用于 .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.

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)

先决条件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 or Windows PowerShell.

设置Setting up

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

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

dotnet new console -n key-vault-console-app

将目录更改为新创建的应用文件夹。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 Azure.Security.KeyVault.Secrets

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

dotnet add package 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.

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 "chinanorth"

az keyvault create --name <your-unique-keyvault-name> -g "myResourceGroup"
New-AzResourceGroup -Name myResourceGroup -Location chinanorth

New-AzKeyVault -Name <your-unique-keyvault-name> -ResourceGroupName myResourceGroup -Location chinanorth

创建服务主体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. 在 Azure 中对桌面应用程序进行身份验证需要使用服务主体和访问控制策略。Authenticating a desktop application with Azure requires the use of a service principal and an access control policy.

使用 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://mySP" --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/"
}

使用 Azure PowerShell 的 New-AzADServicePrincipal 命令创建服务主体:Create a service principal using Azure PowerShell New-AzADServicePrincipal command:

# Create a new service principal
$spn = New-AzADServicePrincipal -DisplayName "http://mySP"

# Get the tenant ID and subscription ID of the service principal
$tenantId = (Get-AzContext).Tenant.Id
$subscriptionId = (Get-AzContext).Subscription.Id

# Get the client ID
$clientId = $spn.ApplicationId

# Get the client Secret
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($spn.Secret)
$clientSecret = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

若要更详细地了解如何使用 Azure PowerShell 来创建服务主体,请参阅使用 Azure PowerShell 创建 Azure 服务主体For more details about the service principal with Azure PowerShell, refer to Create an Azure service principal with Azure PowerShell.

请记下 clientId、clientSecret 和 tenantId,因为我们将在后面的步骤中使用它们。Take note of the clientId, clientSecret, and tenantId, as we will use them in the following steps.

为服务主体授予对 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 list get set delete purge
Set-AzKeyVaultAccessPolicy -VaultName <your-unique-keyvault-name> -ServicePrincipalName <clientId-of-your-service-principal> -PermissionsToSecrets list,get,set,delete,purge

设置环境变量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. 使用将这些变量设置为在上述创建服务主体步骤中记下的 clientId、clientSecret 和 tenantId 值。use set these variables to the clientId, clientSecret, and tenantId values you noted in the Create a service principal step, above.

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

setx AZURE_CLIENT_ID <your-clientID>

setx AZURE_CLIENT_SECRET <your-clientSecret>

setx AZURE_TENANT_ID <your-tenantId>

setx KEY_VAULT_NAME <your-key-vault-name>

每次调用 setx 时,都应会收到响应“成功:已保存指定的值。”Each time you call setx, you should get a response of "SUCCESS: Specified value was saved."

AZURE_CLIENT_ID=<your-clientID>

AZURE_CLIENT_SECRET=<your-clientSecret>

AZURE_TENANT_ID=<your-tenantId>

KEY_VAULT_NAME=<your-key-vault-name>

对象模型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 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:

using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

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

向密钥保管库进行身份验证和创建密钥保管库客户端,依赖于上面设置环境变量步骤中的环境变量。Authenticating to your key vault and creating a key vault client depends on the environmental variables in the Set environmental variables step above. 密钥保管库的名称将扩展为密钥保管库 URI,格式为“https://<your-key-vault-name>.vault.azure.cn”。The name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.cn".

string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.cn";
var credentialOption = new DefaultAzureCredentialOptions();
credentialOption.AuthorityHost = new Uri("https://login.partner.microsoftonline.cn");

var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential(credentialOption));

保存机密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.

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
(Get-AzKeyVaultSecret -VaultName <your-unique-keyvault-name> -Name mySecret).SecretValueText

检索机密Retrieve a secret

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

KeyVaultSecret secret = client.GetSecret(secretName);

机密现已保存为 secret.ValueYour secret is now saved as secret.Value.

删除机密Delete a secret

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

client.StartDeleteSecret(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
(Get-AzKeyVaultSecret -VaultName <your-unique-keyvault-name> -Name mySecret).SecretValueText

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

using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

namespace key_vault_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
            string secretName = "mySecret";

            string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
            var kvUri = "https://" + keyVaultName + ".vault.azure.cn";
            var credentialOption = new DefaultAzureCredentialOptions();
            credentialOption.AuthorityHost = new Uri("https://login.partner.microsoftonline.cn");

            var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential(credentialOption));

            Console.Write("Input the value of your secret > ");
            string secretValue = Console.ReadLine();

            Console.Write("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "` ...");

            client.SetSecret(secretName, secretValue);

            Console.WriteLine(" done.");

            Console.WriteLine("Forgetting your secret.");
            secretValue = "";
            Console.WriteLine("Your secret is '" + secretValue + "'.");

            Console.WriteLine("Retrieving your secret from " + keyVaultName + ".");

            KeyVaultSecret secret = client.GetSecret(secretName);

            Console.WriteLine("Your secret is '" + secret.Value + "'.");

            Console.Write("Deleting your secret from " + keyVaultName + " ...");

            client.StartDeleteSecret(secretName);

            System.Threading.Thread.Sleep(5000);
            Console.WriteLine(" done.");

        }
    }
}

后续步骤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.