使用 Visual Studio 连接服务将 Key Vault 添加到 Web 应用程序Add Key Vault to your web application by using Visual Studio Connected Services

本教程介绍如何轻松添加所需的设置,以开始使用 Azure Key Vault 在 Visual Studio 中管理 Web 项目的机密,不管使用的是 ASP.NET Core 还是任何类型的 ASP.NET 项目。In this tutorial, you will learn how to easily add everything you need to start using Azure Key Vault to manage your secrets for web projects in Visual Studio, whether you are using ASP.NET Core or any type of ASP.NET project. 使用 Visual Studio 中的连接服务功能,可让 Visual Studio 自动添加所需的所有 NuGet 包和配置设置,以连接到 Azure 中的 Key Vault。By using the Connected Services feature in Visual Studio, you can have Visual Studio automatically add all the NuGet packages and configuration settings you need to connect to Key Vault in Azure.

有关连接服务为了启用 Key Vault 而在项目中所做的更改的详细信息,请参阅 Key Vault 连接服务 - 我的 ASP.NET 4.7.1 项目发生了什么情况Key Vault 连接服务 - 我的 ASP.NET Core 项目发生了什么情况For details on the changes that Connected Services makes in your project to enable Key Vault, see Key Vault Connected Service - What happened to my ASP.NET 4.7.1 project or Key Vault Connected Service - What happened to my ASP.NET Core project.

先决条件Prerequisites

  • 一个 Azure 订阅An Azure subscription. 如果没有订阅,可以注册试用帐户If you don't have a subscription, sign up for a trial account.
  • Visual Studio 2019 版本 16.3 或更高版本,或者装有“Web 开发”工作负荷的 Visual Studio 2017 版本 15.7Visual Studio 2019 version 16.3 or later, or Visual Studio 2017 version 15.7 with the Web Development workload installed. 立即下载Download it now.
  • 对于包含 Visual Studio 2017 的 ASP.NET(非 Core),需要安装 .NET Framework 4.7.1 或更高版本的开发工具,默认情况下未安装这些工具。For ASP.NET (not Core) with Visual Studio 2017, you need the .NET Framework 4.7.1 or later Development Tools, which are not installed by default. 若要安装这些工具,请启动 Visual Studio 安装程序,依次选择“修改”、“单个组件”,在右侧展开“ASP.NET 和 Web 开发”,然后选择“.NET Framework 4.7.1 开发工具”。 To install them, launch the Visual Studio Installer, choose Modify, and then choose Individual Components, then on the right-hand side, expand ASP.NET and web development, and choose .NET Framework 4.7.1 Development Tools.
  • 已打开一个 ASP.NET 4.7.1(或更高版本)或 ASP.NET Core 2.0(或更高版本)的 Web 项目。An ASP.NET 4.7.1 or later, or ASP.NET Core 2.0 or later web project open.

将 Key Vault 支持添加到项目Add Key Vault support to your project

在开始之前,请确保已登录 Visual Studio:Before you begin, make sure that you're signed into Visual Studio. 登录时使用的帐户与用于 Azure 订阅的帐户相同。Sign in with the same account that you use for your Azure subscription. 然后打开 ASP.NET 4.7.1 或更高版本或 ASP.NET Core 2.0 Web 项目,执行以下步骤:Then open an ASP.NET 4.7.1 or later, or ASP.NET Core 2.0 web project, and do the follow steps:

  1. 在“解决方案资源管理器”中,右键单击要将 Key Vault 支持添加到的项目,然后选择“添加” > “连接服务”。 In Solution Explorer, right-click the project that you want to add the Key Vault support to, and choose Add > Connected Service. 此时会显示“连接服务”页,其中包含可添加到项目的服务。The Connected Service page appears with services you can add to your project.

  2. 在可用服务的菜单中,选择“使用 Azure Key Vault 来保护机密”。In the menu of available services, choose Secure Secrets With Azure Key Vault.

    选择“使用 Azure Key Vault 来保护机密”

  3. 选择要使用的订阅,然后选择新的或现有的 Key Vault。Select the subscription you want to use, and then choose a new or existing Key Vault. 如果选择新的 Key Vault,则会显示“编辑”链接。If you choose the new Key Vault, an Edit link appears. 选中该链接,以便配置新的 Key Vault。Select it to configure your new Key Vault.

    选择订阅

  4. 在“编辑 Azure Key Vault”中,输入需要用于 Key Vault 的名称。In Edit Azure Key Vault, enter the name you want to use for the Key Vault.

  5. 选择现有资源组,或选择使用自动生成的唯一名称创建新的资源组。Select an existing Resource Group, or choose to create a new one with an automatically generated unique name. 如果想要使用不同的名称创建新组,可以使用 Azure 门户,然后关闭页面并重启,以重新加载资源组列表。If you want to create a new group with a different name, you can use the Azure portal, and then close the page and restart to reload the list of resource groups.

  6. 选择要在其中创建 Key Vault 的“位置”。Choose the Location in which to create the Key Vault. 如果 Web 应用程序托管在 Azure 中,请选择托管 Web 应用程序的区域,以获得最佳性能。If your web application is hosted in Azure, choose the region that hosts the web application for optimum performance.

  7. 选择一个定价层Choose a Pricing tier. 有关详细信息,请参阅 Key Vault 定价For details, see Key Vault Pricing.

  8. 选择“确定”,接受配置选项。Choose OK to accept the configuration choices.

  9. 在 Visual Studio 的“Azure Key Vault”选项卡中选择现有 Key Vault 或配置新的 Key Vault 以后,请选择“添加”,以便添加连接的服务。 After you select an existing Key Vault or have configured a new Key Vault, in the Azure Key Vault tab of Visual Studio, select Add to add the Connected Service.

  10. 选择“管理存储在此 Key Vault 中的机密”链接,打开 Key Vault 的“机密”页。 Select the Manage secrets stored in this Key Vault link to open the Secrets page for your Key Vault. 如果已关闭该页或项目,可以在 Azure 门户中通过选择“安全性”下的“所有服务”导航到它,选择 Key Vault,然后选择你的 Key Vault。If you closed the page or the project, you can navigate to it in the Azure portal by choosing All Services and, under Security, choosing Key Vault, then choose your Key Vault.

  11. 在创建的 Key Vault 的“Key Vault”部分,依次选择“机密”、“生成/导入”。 In the Key Vault section for the Key Vault you created, choose Secrets, then Generate/Import.

    生成/导入机密

  12. 输入一个机密(例如 MySecret),并为其提供任何字符串值作为测试,然后选择“创建”按钮。Enter a secret, such as MySecret and give it any string value as a test, then select the Create button.

    创建机密

  13. (可选)输入另一个机密,但这一次通过将其命名为“Secrets--MySecret”将其放入某个类别。(optional) Enter another secret, but this time put it into a category by naming it Secrets--MySecret. 此语法指定的类别“Secrets”包含机密“MySecret”。This syntax specifies a category "Secrets" that contains a secret "MySecret".

现在,可以在代码中访问机密。Now, you can access your secrets in code. 后续步骤根据使用的是 ASP.NET 4.7.1 还是 ASP.NET Core 而有所不同。The next steps are different depending on whether you are using ASP.NET 4.7.1 or ASP.NET Core.

在代码中访问机密 (ASP.NET Core)Access your secrets in code (ASP.NET Core)

  1. 在解决方案资源管理器中右键单击项目,然后选择“管理 NuGet 包”。In Solution Explorer, right-click on your project, and select Manage NuGet Packages. 在“浏览”选项卡中,找到并安装这两个 NuGet 包:Microsoft.Azure.Services.AppAuthentication;对于 .NET Core 2,请添加 Microsoft.Azure.KeyVault,或者对于 .NET Core 3,请添加 Microsoft.Azure.KeyVault.CoreIn the Browse tab, locate and install these two NuGet packages: Microsoft.Azure.Services.AppAuthentication and for .NET Core 2, add Microsoft.Azure.KeyVault or for .NET Core 3, addMicrosoft.Azure.KeyVault.Core.

  2. 对于 .NET Core 2,请选择 Program.cs 选项卡,然后将 Program 类中的 BuildWebHost 定义更改为以下内容:For .NET Core 2, select the Program.cs tab and change the BuildWebHost definition in the Program class to the following:

         public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((ctx, builder) =>
                {
                    var keyVaultEndpoint = GetKeyVaultEndpoint();
                    if (!string.IsNullOrEmpty(keyVaultEndpoint))
                    {
                        var azureServiceTokenProvider = new AzureServiceTokenProvider();
                        var keyVaultClient = new KeyVaultClient(
                            new KeyVaultClient.AuthenticationCallback(
                                azureServiceTokenProvider.KeyVaultTokenCallback));
                        builder.AddAzureKeyVault(
                            keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                    }
                }
             ).UseStartup<Startup>();
    
         private static string GetKeyVaultEndpoint() => "https://<YourKeyVaultName>.vault.azure.cn";
     }
    

    对于 .NET Core 3,请使用以下代码。For .NET Core 3, use the following code.

         public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((context, config) =>
                 {
                     var keyVaultEndpoint = GetKeyVaultEndpoint();
                     if (!string.IsNullOrEmpty(keyVaultEndpoint))
                     {
                         var azureServiceTokenProvider = new AzureServiceTokenProvider();
                         var keyVaultClient = new KeyVaultClient(
                             new KeyVaultClient.AuthenticationCallback(
                                 azureServiceTokenProvider.KeyVaultTokenCallback));
                         config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                     }
                 })
                 .ConfigureWebHostDefaults(webBuilder =>
                 {
                     webBuilder.UseStartup<Startup>();
                 });
         private static string GetKeyVaultEndpoint() => "https://<YourKeyVaultName>.vault.azure.cn";
    
  3. 接下来打开一个页面文件(例如 Index.cshtml.cs)并编写以下代码:Next open one of the page files, such as Index.cshtml.cs and write the following code:

    1. 通过此 using 指令包含对 Microsoft.Extensions.Configuration 的引用:Include a reference to Microsoft.Extensions.Configuration by this using directive:

      using Microsoft.Extensions.Configuration;
      
    2. 添加配置变量。Add the configuration variable.

      private static IConfiguration _configuration;
      
    3. 添加此构造函数,或将现有的构造函数替换为:Add this constructor or replace the existing constructor with this:

      public IndexModel(IConfiguration configuration)
      {
          _configuration = configuration;
      }
      
    4. 更新 OnGet 方法。Update the OnGet method. 使用在上述命令中创建的机密名称更新此处显示的占位符值。Update the placeholder value shown here with the secret name you created in the above commands.

      public void OnGet()
      {
          ViewData["Message"] = "My key val = " + _configuration["<YourSecretNameThatWasCreatedAbove>"];
      }
      
    5. 若要在运行时确认该值,请在 .cshtml 文件中添加用于显示 ViewData["Message"] 的代码,以显示消息中的机密。To confirm the value at runtime, add code to display ViewData["Message"] to the .cshtml file to display the secret in a message.

          <p>@ViewData["Message"]</p>
      

可以在本地运行应用,以验证是否能够成功地从 Key Vault 获取机密。You can run the app locally to verify that the secret is obtained successfully from the Key Vault.

访问机密 (ASP.NET)Access your secrets (ASP.NET)

可以设置配置,使 web.config 文件中的 appSettings 元素中包含一个虚拟值,在运行时,该值将由 true 值替换。You can set up the configuration so that the web.config file has a dummy value in the appSettings element that is replaced by the true value at runtime. 然后,可以通过 ConfigurationManager.AppSettings 数据结构访问此配置。You can then access this via the ConfigurationManager.AppSettings data structure.

  1. 编辑 web.config 文件。Edit your web.config file. 找到 appSettings 标记,添加属性 configBuilders="AzureKeyVault",然后添加一行:Find the appSettings tag, add an attribute configBuilders="AzureKeyVault", and add a line:

       <add key="mysecret" value="dummy"/>
    
  2. 编辑 HomeController.cs 中的 About 方法,以显示要确认的值。Edit the About method in HomeController.cs, to display the value for confirmation.

    public ActionResult About()
    {
        ViewBag.Message = "Key vault value = " + ConfigurationManager.AppSettings["mysecret"];
    }
    
  3. 在调试器本地运行应用,切换到“关于”选项卡,确认是否显示了 Key Vault 中的值。Run the app locally under the debugger, switch to the About tab, and verify that the value from the Key Vault is displayed.

清理资源Clean up resources

不再需要资源组时,可将其删除。When no longer needed, delete the resource group. 这会删除 Key Vault 和相关的资源。This deletes the Key Vault and related resources. 要通过门户删除资源组,请执行以下操作:To delete the resource group through the portal:

  1. 在门户顶部的“搜索”框中输入资源组的名称。Enter the name of your resource group in the Search box at the top of the portal. 在搜索结果中看到在本快速入门中使用的资源组后,将其选中。When you see the resource group used in this quickstart in the search results, select it.
  2. 选择“删除资源组”。Select Delete resource group.
  3. 在“键入资源组名称”框中,输入资源组的名称,然后选择“删除” 。In the TYPE THE RESOURCE GROUP NAME: box, enter in the name of the resource group and select Delete.

故障排除Troubleshooting

如果运行 Key Vault 的 Microsoft 帐户不是用于登录 Visual Studio 的帐户(例如,Key Vault 在工作帐户中运行,但 Visual Studio 使用的是私人帐户),则 Program.cs 文件中会出现一条错误,指出 Visual Studio 无法访问 Key Vault。If your Key Vault is running on an different Microsoft account than the one you're logged in to Visual Studio (for example, the Key Vault is running on your work account, but Visual Studio is using your private account) you get an error in your Program.cs file, that Visual Studio can't get access to the Key Vault. 解决此问题:To fix this issue:

  1. 转到 Azure 门户并打开 Key Vault。Go to the Azure portal and open your Key Vault.

  2. 依次选择“访问策略”、“添加访问策略”,然后选择用作主体的用于登录的帐户。 Choose Access policies, then Add Access Policy, and choose the account you are logged in with as Principal.

  3. 在 Visual Studio 中,选择“文件” > “帐户设置”。 In Visual Studio, choose File > Account Settings. 在“所有帐户”部分选择“添加帐户”。 Select Add an account from the All account section. 使用选作访问策略主体的帐户登录。Sign in with the account you have chosen as Principal of your access policy.

  4. 选择“工具” > “选项”,找到“Azure 服务身份验证”。 Choose Tools > Options, and look for Azure Service Authentication. 然后选择刚刚添加到 Visual Studio 的帐户。Then select the account you just added to Visual Studio.

现在,在调试应用程序时,Visual Studio 将连接到 Key Vault 所在的帐户。Now, when you debug your application, Visual Studio connects to the account your Key Vault is located on.

如何修改 ASP.NET Core 项目How your ASP.NET Core project is modified

此部分介绍在使用 Visual Studio 添加 Key Vault 连接服务时,对 ASP.NET 项目所做的具体更改。This section identifies the exact changes made to an ASP.NET project when adding the Key Vault connected service using Visual Studio.

为 ASP.NET Core 添加了引用Added references for ASP.NET Core

影响项目文件 .NET 引用和 NuGet 包引用。Affects the project file .NET references and NuGet package references.

类型Type 参考Reference
NuGetNuGet Microsoft.AspNetCore.AzureKeyVault.HostingStartupMicrosoft.AspNetCore.AzureKeyVault.HostingStartup

为 ASP.NET Core 添加了文件Added files for ASP.NET Core

  • 添加了 ConnectedService.json,其中记录了有关连接服务提供程序、版本和指向文档的链接的一些信息。ConnectedService.json added, which records some information about the Connected Service provider, version, and a link the documentation.

ASP.NET Core 的项目文件更改Project file changes for ASP.NET Core

  • 添加了连接服务 ItemGroup 和 ConnectedServices.json 文件。Added the Connected Services ItemGroup and ConnectedServices.json file.

适用于 ASP.NET Core 的 launchsettings.json 更改launchsettings.json changes for ASP.NET Core

  • 将以下环境变量条目添加到 IIS Express 配置文件和匹配 Web 项目名称的配置文件:Added the following environment variable entries to both the IIS Express profile and the profile that matches your web project name:

      "environmentVariables": {
        "ASPNETCORE_HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONENABLED": "true",
        "ASPNETCORE_HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONVAULT": "<your keyvault URL>"
      }
    

Azure 上适用于 ASP.NET Core 的更改Changes on Azure for ASP.NET Core

  • 创建了资源组(或使用了现有资源组)。Created a resource group (or used an existing one).
  • 在指定的资源组中创建了密钥保管库。Created a Key Vault in the specified resource group.

如何修改 ASP.NET Framework 项目How your ASP.NET Framework project is modified

此部分介绍在使用 Visual Studio 添加 Key Vault 连接服务时,对 ASP.NET 项目所做的具体更改。This section identifies the exact changes made to an ASP.NET project when adding the Key Vault connected service using Visual Studio.

为 ASP.NET Framework 添加了引用Added references for ASP.NET Framework

影响项目文件 .NET 引用和 packages.config(NuGet 引用)。Affects the project file .NET references and packages.config (NuGet references).

类型Type 参考Reference
.NET; NuGet.NET; NuGet Microsoft.Azure.KeyVaultMicrosoft.Azure.KeyVault
.NET; NuGet.NET; NuGet Microsoft.Azure.KeyVault.WebKeyMicrosoft.Azure.KeyVault.WebKey
.NET; NuGet.NET; NuGet Microsoft.Rest.ClientRuntimeMicrosoft.Rest.ClientRuntime
.NET; NuGet.NET; NuGet Microsoft.Rest.ClientRuntime.AzureMicrosoft.Rest.ClientRuntime.Azure

为 ASP.NET Framework 添加了文件Added files for ASP.NET Framework

  • 添加了 ConnectedService.json,其中记录了有关连接服务提供程序、版本和指向文档的链接的一些信息。ConnectedService.json added, which records some information about the Connected Service provider, version, and a link to the documentation.

ASP.NET Framework 的项目文件更改Project file changes for ASP.NET Framework

  • 添加了连接服务 ItemGroup 和 ConnectedServices.json 文件。Added the Connected Services ItemGroup and ConnectedServices.json file.
  • 请参考添加的引用部分中所述的 .NET 程序集。References to the .NET assemblies described in the Added references section.

web.config 或 app.config 发生更改web.config or app.config changes

  • 添加了以下配置条目:Added the following configuration entries:

    <configSections>
      <section
           name="configBuilders"
           type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           restartOnExternalChanges="false"
           requirePermission="false" />
    </configSections>
    <configBuilders>
      <builders>
        <add
             name="AzureKeyVault"
             vaultName="vaultname"
             type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=1.0.0.0, Culture=neutral"
             vaultUri="https://vaultname.vault.azure.cn" />
      </builders>
    </configBuilders>
    

Azure 上适用于 ASP.NET Framework 的更改Changes on Azure for ASP.NET Framework

  • 创建了资源组(或使用了现有资源组)。Created a resource group (or used an existing one).
  • 在指定的资源组中创建了密钥保管库。Created a Key Vault in the specified resource group.

后续步骤Next steps

如果已根据本教程完成上述操作,则为你设置的 Key Vault 权限适合与你自己的 Azure 订阅配合运行,但可能不适合于生产方案。If you followed this tutorial, your Key Vault permissions are set up to run with your own Azure subscription, but that might not be desirable for a production scenario. 可以创建托管标识来管理应用的 Key Vault 访问权限。You can create a managed identity to manage Key Vault access for your app. 请参阅使用托管标识提供 Key Vault 身份验证See Provide Key Vault authentication with a managed identity.

Key Vault 开发人员指南中了解如何使用 Key Vault 进行开发。Learn more about Key Vault development by reading the Key Vault Developer's Guide.