教程:如何将 Azure Key Vault 与 .NET Azure Web 应用配合使用Tutorial: Use Azure Key Vault with an Azure web app in .NET

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

本教程介绍如何创建可从 Azure Key Vault 读取信息的 Azure Web 应用程序。In this tutorial, you learn how to create an Azure web application that can read information from an Azure key vault. 该过程使用 Azure 资源的托管标识。The process uses managed identities for Azure resources. 有关 Azure Web 应用的详细信息,请参阅 Azure 应用服务For more information about Azure web applications, see Azure App Service.

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

  • 创建密钥保管库。Create a key vault.
  • 将机密添加到 Key Vault。Add a secret to the key vault.
  • 从密钥保管库检索机密。Retrieve a secret from the key vault.
  • 创建 Azure Web 应用。Create an Azure web app.
  • 为 Web 应用启用托管标识。Enable a managed identity for the web app.
  • 为 Web 应用分配权限。Assign permission for the web app.
  • 在 Azure 上运行 Web 应用。Run the web app on Azure.

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

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

先决条件Prerequisites

关于托管服务标识About Managed Service Identity

Azure Key Vault 可以安全地存储凭据,因此不需要在代码中显示凭据。Azure Key Vault stores credentials securely, so they're not displayed in your code. 但是,需要对 Azure Key Vault 进行身份验证才能检索密钥。However, you need to authenticate to Azure Key Vault to retrieve your keys. 若要对 Key Vault 进行身份验证,需要提供凭据。To authenticate to Key Vault, you need a credential. 因此,在启动过程中,这是一个难以兼顾的典型问题。It's a classic bootstrap dilemma. 托管服务标识 (MSI) 提供简化该过程的启动标识,可以解决此问题。 Managed Service Identity (MSI) solves this issue by providing a bootstrap identity that simplifies the process.

为 Azure 服务(例如 Azure 虚拟机、Azure 应用服务或 Azure Functions)启用 MSI 时,Azure 会创建一个服务主体When you enable MSI for an Azure service, such as Azure Virtual Machines, Azure App Service, or Azure Functions, Azure creates a service principal. MSI 针对 Azure Active Directory (Azure AD) 中的服务实例提供启动标识,并将服务主体凭据注入该实例。MSI does this for the instance of the service in Azure Active Directory (Azure AD) and injects the service principal credentials into that instance.

MSI 示意图

接下来,为了获取访问令牌,代码会调用 Azure 资源上提供的本地元数据服务。Next, to get an access token, your code calls a local metadata service that's available on the Azure resource. 代码使用从本地 MSI 终结点获取的访问令牌,以便向 Azure Key Vault 服务进行身份验证。Your code uses the access token that it gets from the local MSI endpoint to authenticate to an Azure Key Vault service.

登录 AzureLog in to Azure

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

az cloud set -n AzureChinaCloud
az login

创建资源组Create a resource group

Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container into which Azure resources are deployed and managed.

使用 az group create 命令创建资源组。Create a resource group by using the az group create command.

接下来,选择一个资源组名称,然后将其填充在占位符中。Then, select a resource group name and fill in the placeholder. 以下示例在“中国北部”位置创建一个资源组:The following example creates a resource group in the China North location:

# To list locations: az account list-locations --output table
az group create --name "<YourResourceGroupName>" --location "China North"

本教程通篇使用此资源组。You use this resource group throughout this tutorial.

创建密钥保管库Create a key vault

若要在资源组中创建 Key Vault,请提供以下信息:To create a key vault in your resource group, provide the following information:

  • Key Vault 名称:由 3 到 24 个字符构成的字符串,可以包含数字 (0-9)、字母 (a-z, A-Z) 和连字符 (-)Key vault name: a string of 3 to 24 characters that can contain only numbers (0-9), letters (a-z, A-Z), and hyphens (-)
  • 资源组名称Resource group name
  • 位置:华北Location: China North

在 Azure CLI 中输入以下命令:In the Azure CLI, enter the following command:

az keyvault create --name "<YourKeyVaultName>" --resource-group "<YourResourceGroupName>" --location "China North"

目前,只有你的 Azure 帐户才有权对这个新保管库执行操作。At this point, your Azure account is the only one that's authorized to perform operations on this new vault.

向密钥保管库添加机密Add a secret to the key vault

现在可以添加机密。Now you can add a secret. 机密可以是 SQL 连接字符串,或者需要安全保存的、可供应用程序使用的其他任何信息。It might be a SQL connection string or any other information that you need to keep both secure and available to your application.

若要在名为 AppSecret 的 Key Vault 中创建机密,请输入以下命令:To create a secret in the key vault called AppSecret, enter the following command:

az keyvault secret set --vault-name "<YourKeyVaultName>" --name "AppSecret" --value "MySecret"

此机密将存储值 MySecretThis secret stores the value MySecret.

若要查看机密中包含的纯文本形式的值,请输入以下命令:To view the value that's contained in the secret as plain text, enter the following command:

az keyvault secret show --name "AppSecret" --vault-name "<YourKeyVaultName>"

此命令显示机密信息,包括 URI。This command displays the secret information, including the URI.

完成这些步骤后,密钥保管库中会出现某个机密的 URI。After you complete these steps, you should have a URI to a secret in a key vault. 请记下此信息,因为本教程稍后需要用到。Make note of this information for later use in this tutorial.

创建 .NET Core Web 应用Create a .NET Core web app

若要创建 .NET Core Web 应用并将其发布到 Azure,请遵照在 Azure 中创建 ASP.NET Core Web 应用中的说明。To create a .NET Core web app and publish it to Azure, follow the instructions in Create an ASP.NET Core web app in Azure.

打开并编辑解决方案Open and edit the solution

  1. 转到“Pages” > “About.cshtml.cs”文件。 Go to the Pages > About.cshtml.cs file.

  2. 安装以下 NuGet 包:Install these NuGet packages:

  3. About.cshtml.cs 文件中导入以下代码:Import the following code to the About.cshtml.cs file:

     using Microsoft.Azure.KeyVault;
     using Microsoft.Azure.KeyVault.Models;
     using Microsoft.Azure.Services.AppAuthentication;
    

    AboutModel 类中的代码应如下所示:Your code in the AboutModel class should look like this:

     public class AboutModel : PageModel
     {
         public string Message { get; set; }
    
         public async Task OnGetAsync()
         {
             Message = "Your application description page.";
             int retries = 0;
             bool retry = false;
             try
             {
                 /* The next four lines of code show you how to use AppAuthentication library to fetch secrets from your key vault */
                 AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                 KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                 var secret = await keyVaultClient.GetSecretAsync("https://<YourKeyVaultName>.vault.azure.cn/secrets/AppSecret")
                         .ConfigureAwait(false);
                 Message = secret.Value;
             }
             /* If you have throttling errors see this tutorial https://docs.azure.cn/key-vault/tutorial-net-create-vault-azure-web-app */
             /// <exception cref="KeyVaultErrorException">
             /// Thrown when the operation returned an invalid status code
             /// </exception>
             catch (KeyVaultErrorException keyVaultException)
             {
                 Message = keyVaultException.Message;
             }
         }
    
         // This method implements exponential backoff if there are 429 errors from Azure Key Vault
         private static long getWaitTime(int retryCount)
         {
             long waitTime = ((long)Math.Pow(2, retryCount) * 100L);
             return waitTime;
         }
    
         // This method fetches a token from Azure Active Directory, which can then be provided to Azure Key Vault to authenticate
         public async Task<string> GetAccessTokenAsync()
         {
             var azureServiceTokenProvider = new AzureServiceTokenProvider();
             string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.cn");
             return accessToken;
         }
     }
    

运行 Web 应用Run the web app

  1. 在 Visual Studio 2019 的主菜单中,选择“调试” > “开始执行(调试)”或“开始执行(不调试)” 。On the main menu of Visual Studio 2019, select Debug > Start, with or without debugging.
  2. 在浏览器中,转到“关于”页。 In the browser, go to the About page.
    此时会显示 AppSecret 的值。The value for AppSecret is displayed.

启用托管标识Enable a managed identity

虽然 Azure Key Vault 提供安全存储凭据及其他机密的方式,但代码需要对 Key Vault 进行身份验证才能检索这些凭据和机密。Azure Key Vault provides a way to securely store credentials and other secrets, but your code needs to authenticate to Key Vault to retrieve them. Azure 资源的托管标识概述可帮助你解决此问题,其中介绍了如何在 Azure AD 中为 Azure 服务提供自动托管的标识。Managed identities for Azure resources overview helps to solve this problem by giving Azure services an automatically managed identity in Azure AD. 此标识可用于通过支持 Azure AD 身份验证的任何服务(包括 Key Vault)的身份验证,这样就无需在代码中插入任何凭据了。You can use this identity to authenticate to any service that supports Azure AD authentication, including Key Vault, without having to display credentials in your code.

在 Azure CLI 中,若要为此应用程序创建标识,请运行 assign-identity 命令:In the Azure CLI, to create the identity for this application, run the assign-identity command:

az webapp identity assign --name "<YourAppName>" --resource-group "<YourResourceGroupName>"

请将 <YourAppName> 替换为 Azure 上发布的应用的名称。Replace <YourAppName> with the name of the published app on Azure.
例如,如果发布的应用名为 MyAwesomeapp.chinacloudsites.cn,请将 <YourAppName> 替换为 MyAwesomeappFor example, if your published app name was MyAwesomeapp.chinacloudsites.cn, replace <YourAppName> with MyAwesomeapp.

将应用程序发布到 Azure 时,请记下 PrincipalIdMake a note of the PrincipalId when you publish the application to Azure. 步骤 1 中命令的输出应采用以下格式:The output of the command in step 1 should be in the following format:

{
  "principalId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "type": "SystemAssigned"
}

备注

此过程中的命令等同于转到 Azure 门户并在 Web 应用程序属性中将“标识/系统分配”设置切换为“打开” 。 The command in this procedure is the equivalent of going to the Azure portal and switching the Identity / System assigned setting to On in the web application properties.

向应用分配权限Assign permissions to your app

在以下命令中,请将 <YourKeyVaultName> 替换为 Key Vault 的名称,将 <PrincipalId> 替换为 PrincipalId 的值:Replace <YourKeyVaultName> with the name of your key vault, and replace <PrincipalId> with the value of the PrincipalId in the following command:

az keyvault set-policy --name '<YourKeyVaultName>' --object-id <PrincipalId> --secret-permissions get list

此命令为应用服务的标识 (MSI) 提供针对 Key Vault 执行 getlist 操作的权限。This command gives the identity (MSI) of the app service permission to do get and list operations on your key vault.

将 Web 应用发布到 AzurePublish the web app to Azure

再次将 Web 应用发布到 Azure,以验证实时 Web 应用是否可以提取机密值。Publish your web app to Azure once again to verify that your live web app can fetch the secret value.

  1. 在 Visual Studio 中选择 key-vault-dotnet-core-quickstart 项目。In Visual Studio, select the key-vault-dotnet-core-quickstart project.
  2. 选择“发布” > “开始”。Select Publish > Start.
  3. 选择“创建” 。Select Create.

运行该应用程序时应会看到,它可以检索机密值。When you run the application, you should see that it can retrieve your secret value.

现已成功地在 .NET 中创建一个 Web 应用,该应用可在 Key Vault 中存储和提取其机密。Now, you've successfully created a web app in .NET that stores and fetches its secrets from your key vault.

清理资源Clean up resources

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

后续步骤Next steps