创建服务主体Create a service principal

对基于云的 .NET 应用程序进行身份验证的最简单方法是使用托管标识；有关详细信息，请参阅使用应用服务托管标识访问 Azure Key Vault。The 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.

通过将 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.

设置环境变量Set environmental variables

应用程序中的 DefaultAzureCredential 方法依赖于三个环境变量：AZURE_CLIENT_ID、AZURE_CLIENT_SECRET 和 AZURE_TENANT_ID。The 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;

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

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

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