你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:适用于 .NET 的 Azure 密钥保管库机密客户端库

开始使用适用于 .NET 的 Azure Key Vault 机密客户端库。 Azure Key Vault 是一项云服务,它为机密提供了安全的存储。 可以安全地存储密钥、密码、证书和其他机密。 可以通过 Azure 门户创建和管理 Azure Key Vault。 本快速入门介绍如何使用 .NET 客户端库在 Azure 密钥保管库中创建、检索和删除机密

Key Vault 客户端库资源:

API 参考文档 | 库源代码 | 包 (NuGet)

有关 Key Vault 和机密的详细信息,请参阅:

先决条件

本快速入门使用 dotnet 和 Azure CLI 或 Azure PowerShell。

设置

本快速入门结合使用 Azure Identity 库和 Azure CLI,向 Azure 服务验证用户身份。 开发人员还可以使用 Visual Studio 或 Visual Studio Code 来验证其调用。有关详细信息,请参阅使用 Azure Identity 客户端库对客户端进行身份验证

登录 Azure

  1. 运行 az login 命令。

    az login
    

    如果 CLI 可以打开默认浏览器,它将这样做并加载 Azure 登录页。

    否则,请在 https://aka.ms/devicelogin 处打开浏览器页,然后输入终端中显示的授权代码。

  2. 在浏览器中使用帐户凭据登录。

授予对 Key Vault 的访问权限

若要通过基于角色的访问控制 (RBAC) 授予应用程序对密钥保管库的权限,请使用 Azure CLI 命令 az role assignment create 分配角色。

az role assignment create --role "Key Vault Secrets User" --assignee "<app-id>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

将 <app-id>、<subscription-id>、<resource-group-name> 和 <your-unique-keyvault-name> 替换为你的实际值。 <app-id> 是你在 Azure AD 中注册的应用程序的“应用程序(客户端) ID”。

创建新的 .NET 控制台应用

  1. 在命令外壳中,运行以下命令以创建名为 key-vault-console-app 的项目:

    dotnet new console --name key-vault-console-app
    
  2. 切换到新创建的 key-vault-console-app 目录,然后运行以下命令来生成项目:

    dotnet build
    

    生成输出不应包含警告或错误。

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

安装包

在命令外壳中,安装适用于 .NET 的 Azure Key Vault 机密客户端库:

dotnet add package Azure.Security.KeyVault.Secrets

对于本快速入门,还需要安装 Azure 标识客户端库:

dotnet add package Azure.Identity

设置环境变量

此应用程序使用 Key Vault 名称作为名为 KEY_VAULT_NAME 的环境变量。

Windows

set KEY_VAULT_NAME=<your-key-vault-name>

Windows PowerShell

$Env:KEY_VAULT_NAME="<your-key-vault-name>"

macOS 或 Linux

export KEY_VAULT_NAME=<your-key-vault-name>

对象模型

适用于 .NET 的 Azure Key Vault 机密客户端库可用于管理机密。 代码示例部分介绍如何创建客户端以及设置、检索和删除密码。

代码示例

添加指令

在 Program.cs 的顶部添加以下指令:

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

进行身份验证并创建客户端

对大多数 Azure 服务的应用程序请求必须获得授权。 要在代码中实现与 Azure 服务的无密码连接,建议使用 Azure 标识客户端库提供的 DefaultAzureCredential 类。 DefaultAzureCredential 支持多种身份验证方法,并确定应在运行时使用哪种方法。 通过这种方法,你的应用可在不同环境(本地与生产)中使用不同的身份验证方法,而无需实现特定于环境的代码。

在本快速入门中,DefaultAzureCredential 使用登录到 Azure CLI 的本地开发用户的凭据对密钥保管库进行身份验证。 将应用程序部署到 Azure 时,相同的 DefaultAzureCredential 代码可以自动发现并使用分配给应用服务、虚拟机或其他服务的托管标识。 有关详细信息,请参阅托管标识概述

在此示例中,密钥保管库的名称扩展为密钥保管库 URI,格式为 https://<your-key-vault-name>.vault.azure.net。 有关向密钥保管库进行身份验证的详细信息,请参阅开发人员指南

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

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

保存机密

控制台应用已通过身份验证,接下来将密码添加到 Key Vault 中。 对于此任务,请使用 SetSecretAsync 方法。

该方法的第一个参数接受机密的名称。 在此示例中,变量 secretName 存储字符串“mySecret”。

该方法的第二个参数接受机密的值。 在此示例中,机密由用户通过命令行输入,并存储在变量 secretValue 中。

await client.SetSecretAsync(secretName, secretValue);

注意

如果机密名已存在,则该代码将创建该机密的新版本。

检索机密

现在,可以使用 GetSecretAsync 方法检索以前设置的值。

var secret = await client.GetSecretAsync(secretName);

机密现已保存为 secret.Value

删除机密

最后,使用 StartDeleteSecretAsyncPurgeDeletedSecretAsync 方法从 Key Vault 中删除机密。

var operation = await client.StartDeleteSecretAsync(secretName);
// You only need to wait for completion if you want to purge or recover the key.
await operation.WaitForCompletionAsync();

await client.PurgeDeletedSecretAsync(secretName);

示例代码

通过完成以下步骤,将 .NET 控制台应用修改为与密钥保管库交互:

  1. 将 Program.cs 中的代码替换为以下代码:

    using System;
    using System.Threading.Tasks;
    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    
    namespace key_vault_console_app
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                const string secretName = "mySecret";
                var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
                var kvUri = $"https://{keyVaultName}.vault.azure.net";
    
                var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
    
                Console.Write("Input the value of your secret > ");
                var secretValue = Console.ReadLine();
    
                Console.Write($"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ...");
                await client.SetSecretAsync(secretName, secretValue);
                Console.WriteLine(" done.");
    
                Console.WriteLine("Forgetting your secret.");
                secretValue = string.Empty;
                Console.WriteLine($"Your secret is '{secretValue}'.");
    
                Console.WriteLine($"Retrieving your secret from {keyVaultName}.");
                var secret = await client.GetSecretAsync(secretName);
                Console.WriteLine($"Your secret is '{secret.Value.Value}'.");
    
                Console.Write($"Deleting your secret from {keyVaultName} ...");
                DeleteSecretOperation operation = await client.StartDeleteSecretAsync(secretName);
                // You only need to wait for completion if you want to purge or recover the secret.
                await operation.WaitForCompletionAsync();
                Console.WriteLine(" done.");
    
                Console.Write($"Purging your secret from {keyVaultName} ...");
                await client.PurgeDeletedSecretAsync(secretName);
                Console.WriteLine(" done.");
            }
        }
    }
    

测试和验证

  1. 执行以下命令来运行应用。

    dotnet run
    
  2. 出现提示时,输入一个密码值。 例如,mySecretPassword。

随即显示以下输出的变体:

Input the value of your secret > mySecretPassword
Creating a secret in <your-unique-keyvault-name> called 'mySecret' with the value 'mySecretPassword' ... done.
Forgetting your secret.
Your secret is ''.
Retrieving your secret from <your-unique-keyvault-name>.
Your secret is 'mySecretPassword'.
Deleting your secret from <your-unique-keyvault-name> ... done.    
Purging your secret from <your-unique-keyvault-name> ... done.

后续步骤

若要详细了解 Key Vault 以及如何将其与应用集成,请参阅以下文章: