通过


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

教程:在 .NET 中将Azure 密钥保管库与虚拟机配合使用

Azure 密钥保管库可帮助保护机密,例如 API 密钥、访问应用程序、服务和 IT 资源所需的数据库连接字符串。

本教程介绍如何获取控制台应用程序以从Azure 密钥保管库读取信息。 应用程序将使用虚拟机管理的身份来验证对 密钥保管库 的访问。

本教程介绍如何:

  • 创建资源组。
  • 创建密钥保管库。
  • 将机密添加到 Key Vault。
  • 从密钥保管库检索机密。
  • 创建Azure虚拟机。
  • 为虚拟机启用托管标识
  • 为 VM 标识分配权限。

在开始之前,请阅读 密钥保管库 基本概念

如果没有Azure订阅,请创建一个 free 帐户

先决条件

对于 Windows、Mac 和 Linux:

创建资源并分配权限

在开始编码之前,需要创建一些资源,将机密放入密钥保管库,并分配权限。

登录到 Azure

使用以下命令登录到Azure:

az login

创建资源组和 Key Vault

本快速入门使用预先创建的Azure密钥保管库。 可以按照以下快速入门中的步骤创建密钥保管库:

或者,可以运行这些Azure CLI或Azure PowerShell命令。

重要

每个密钥保管库必须具有唯一的名称。 在以下示例中,将 <vault-name> 替换为您的密钥保管库的名称。

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<vault-name>" -g "myResourceGroup" --enable-rbac-authorization true

使用机密填充密钥保管库

让我们创建一个名为 mySecret 的机密,其值为 Success!。 机密可能是密码、SQL连接字符串或任何其他信息,您需要确保这些内容对应用程序既安全又可用。

若要将机密添加到新创建的密钥保管库,请使用以下命令:

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

创建虚拟机

使用以下方法之一创建Windows或 Linux 虚拟机:

Windows Linux
Azure CLI Azure CLI
PowerShell PowerShell
Azure 门户 Azure 门户

为 VM 分配标识

按照以下示例为虚拟机创建系统分配的标识:

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

记下以下代码中显示的系统分配的标识。 以上命令的输出为:

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

为 VM 标识分配权限

若要通过 Role-Based 访问控制 (RBAC)获取密钥保管库的权限,请使用 Azure CLI 命令az 角色分配创建为“用户主体名称”(UPN)分配角色。

az role assignment create --role "Key Vault Secrets User" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/<vault-name>"

替换<upn><subscription-id><vault-name>为实际值。 如果使用了其他资源组名称,请替换“myResourceGroup”。 你的 UPN 通常采用电子邮件地址格式(例如 username@domain.com)。

登录到虚拟机

若要登录到虚拟机,请按照 Connect 中的说明登录到 Azure Windows 虚拟机Connect 并登录到 Azure Linux 虚拟机

设置控制台应用

创建控制台应用并使用 dotnet 命令安装所需的包。

安装 .NET Core

若要安装 .NET Core,请转到 .NET 下载页。

创建并运行示例.NET应用

打开命令提示符。

可以通过运行以下命令将“Hello World”打印到控制台:

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

安装软件包

在控制台窗口中,安装用于.NET的 Azure 密钥保管库 机密客户端库:

dotnet add package Azure.Security.KeyVault.Secrets

在本快速入门中,需要安装以下标识包才能对Azure 密钥保管库进行身份验证:

dotnet add package Azure.Identity

编辑控制台应用

打开 Program.cs 文件,添加以下包:

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

添加以下行,更新 URI 以反映密钥保管库的 vaultUri。 下面的代码使用 'DefaultAzureCredential()' 对密钥保管库进行身份验证,使用来自应用程序托管标识的令牌来完成认证。 它还在密钥保管库受到限制的情况下将指数退避用于重试。

  class Program
    {
        static void Main(string[] args)
        {
            string secretName = "mySecret";
            string keyVaultName = "<vault-name>";
            var kvUri = "https://<vault-name>.vault.azure.net";
            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.");

        }
    }

清理资源

不再需要时,请删除虚拟机和密钥保管库。

后续步骤