教程:将 Azure Key Vault 与通过 .NET 编写的虚拟机配合使用Tutorial: Use Azure Key Vault with a virtual machine in .NET

Azure Key Vault 可以帮助保护机密,例如访问应用程序、服务和 IT 资源时所需的 API 密钥与数据库连接字符串。Azure Key Vault helps you to protect secrets such as API keys, the database connection strings you need to access your applications, services, and IT resources.

本教程介绍如何获取控制台应用程序,以便从 Azure Key Vault 读取信息。In this tutorial, you learn how to get a console application to read information from Azure Key Vault. 应用程序将使用虚拟机托管标识对 Key Vault 进行身份验证。Application would use virtual machine managed identity to authenticate to Key Vault.

本教程介绍如何:The tutorial shows you how to:

  • 创建资源组。Create a resource group.
  • 创建密钥保管库。Create a key vault.
  • 将机密添加到 Key Vault。Add a secret to the key vault.
  • 从密钥保管库检索机密。Retrieve a secret from the key vault.
  • 创建一个 Azure 虚拟机。Create an Azure virtual machine.
  • 为虚拟机启用托管标识Enable a managed identity for the Virtual Machine.
  • 为 VM 标识分配权限。Assign permissions to the VM identity.

在开始之前,请阅读 Key Vault 的基本概念Before you begin, read Key Vault basic concepts.

如果没有 Azure 订阅,请创建一个试用帐户If you don’t have an Azure subscription, create a trial account.

先决条件Prerequisites

对于 Windows、Mac 和 Linux:For Windows, Mac, and Linux:

创建资源并分配权限Create resources and assign permissions

在开始编码之前,需要创建一些资源,将机密放入密钥保管库,并分配权限。Before you start coding you need to create some resources, put a secret into your key vault, and assign permissions.

登录 AzureSign in to Azure

若要使用 Azure CLI 登录到 Azure,请输入:To sign in to Azure by using the Azure CLI, enter:

az cloud set –n  AzureChinaCloud 
az login

创建资源组和 Key VaultCreate a resource group and key vault

This quickstart uses a pre-created 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.

Alternatively, you can simply run the Azure CLI or Azure PowerShell commands below.

重要

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"
New-AzResourceGroup -Name myResourceGroup -Location ChinaEast

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

使用机密填充密钥保管库Populate your key vault with a secret

Let's create a secret called mySecret, with a value of Success!. A secret might be a password, a SQL connection string, or any other information that you need to keep both secure and available to your application.

To add a secret to your newly created key vault, use the Azure CLI az keyvault secret set command:

az keyvault secret set --vault-name "<your-unique-keyvault-name>" --name "mySecret" --value "Success!"

创建虚拟机Create a virtual machine

使用以下方法之一创建 Windows 或 Linux 虚拟机:Create a Windows or Linux virtual machine using one of the following methods:

WindowsWindows LinuxLinux
Azure CLIAzure CLI Azure CLIAzure CLI
PowerShellPowerShell PowerShellPowerShell
Azure 门户Azure portal Azure 门户Azure portal

为 VM 分配标识Assign an identity to the VM

使用 az vm identity assign 命令为虚拟机创建系统分配的标识:Create a system-assigned identity for the virtual machine with the az vm identity assign command:

az vm identity assign --name <NameOfYourVirtualMachine> --resource-group <YourResourceGroupName>

记下以下代码中显示的系统分配的标识。Note the system-assigned identity that's displayed in the following code. 以上命令的输出为:The output of the preceding command would be:

{
  "systemAssignedIdentity": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "userAssignedIdentities": {}
}

为 VM 标识分配权限Assign permissions to the VM identity

使用 az keyvault set-policy 命令将以前创建的标识权限分配给密钥保管库:Assign the previously created identity permissions to your key vault with the az keyvault set-policy command:

az keyvault set-policy --name '<your-unique-key-vault-name>' --object-id <VMSystemAssignedIdentity> --secret-permissions get list

登录到虚拟机Sign in to the virtual machine

若要登录到虚拟机,请按照连接并登录到 Azure Windows 虚拟机中的说明操作。To sign in to the virtual machine, follow the instructions in Connect and sign in to an Azure Windows virtual machine.

设置控制台应用Set up the console app

创建控制台应用并使用 dotnet 命令安装所需的包。Create a console app and install the required packages using the dotnet command.

安装 .NET CoreInstall .NET Core

若要安装 .NET Core,请转到 .NET 下载页。To install .NET Core, go to the .NET downloads page.

创建并运行示例 .NET 应用Create and run a sample .NET app

打开命令提示符。Open a command prompt.

可以运行以下命令,将“Hello World”输出到控制台:You can print "Hello World" to the console by running the following commands:

dotnet new console -n keyvault-console-app
cd keyvault-console-app
dotnet run

安装包Install the package

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

dotnet add package Azure.Security.KeyVault.Secrets

对于本快速入门,你将需要安装以下标识包,以对 Azure Key Vault 进行身份验证:For this quickstart, you will need to install the following identity package to authenticate to Azure Key Vault:

dotnet add package Azure.Identity

编辑控制台应用Edit the console app

打开 Program.cs 文件,添加以下包:Open the Program.cs file and add these packages:

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

添加以下行,更新 URI 以反映密钥保管库的 vaultUriAdd these lines, updating the URI to reflect the vaultUri of your key vault. 下面的代码将 DefaultAzureCredential() 用于向密钥保管库进行身份验证,该类使用来自应用程序托管标识的令牌进行身份验证。Below code is using 'DefaultAzureCredential()' for authentication to key vault, which is using token from application managed identity to authenticate. 它还在密钥保管库受到限制的情况下将指数退避用于重试。It is also using exponential backoff for retries in case of key vault is being throttled.

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

            var kvUri = "https://<your-key-vault-name>.vault.azure.cn";
            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                {
                    Delay= TimeSpan.FromSeconds(2),
                    MaxDelay = TimeSpan.FromSeconds(16),
                    MaxRetries = 5,
                    Mode = RetryMode.Exponential
                 }
            };

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

            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.");

        }
    }

清理资源Clean up resources

不再需要本教程中创建的虚拟机和 Key Vault 时,请将其删除。When they are no longer needed, delete the virtual machine and your key vault.

后续步骤Next steps