使用 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

将 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 > Add. 此时会显示“连接服务”页,其中包含可添加到项目的服务。The Connected Service page appears with services you can add to your project.

  2. 在可用服务的菜单中,选择“Azure Key Vault”,然后单击“下一步”。In the menu of available services, choose Azure Key Vault and click Next.

    选择“Azure Key Vault”

  3. 选择要使用的订阅,接着选择现有的 Key Vault,然后单击“完成”。Select the subscription you want to use, and then choose a existing Key Vault and click Finish.

    选择订阅

现在已建立与 Key Vault 的连接,你可以通过代码访问机密了。Now, connection to Key Vault is established and 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. 打开页面文件之一(例如 Index.cshtml.cs)并编写以下代码: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["<YourSecretNameStoredInKeyVault>"];
      }
      
    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. 在解决方案资源管理器中右键单击项目,然后选择“管理 NuGet 包”。In Solution Explorer, right-click on your project, and select Manage NuGet Packages. 在“浏览”选项卡中,找到并安装 Microsoft.Configuration.ConfigurationBuilders.AzureIn the Browse tab, locate and install Microsoft.Configuration.ConfigurationBuilders.Azure

  2. 打开 web.config 文件并编写以下代码:Open your web.config file, and write the following code:

    1. 添加 configSectionsconfigBuildersAdd configSections and configBuilders:
       <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>
      
    2. 找到 appSettings 标记,添加属性 configBuilders="AzureKeyVault",然后添加一行:Find the appSettings tag, add an attribute configBuilders="AzureKeyVault", and add a line:
       <add key="<secretNameInYourKeyVault>" value="dummy"/>
      
  3. 编辑 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["<secretNameInYourKeyVault>"];
    }
    
  4. 在调试器本地运行应用,切换到“关于”选项卡,确认是否显示了 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.

故障排除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 Azure.IdentityAzure.Identity
.NET; NuGet.NET; NuGet Azure.Security.KeyVault.KeysAzure.Security.KeyVault.Keys
.NET; NuGet.NET; NuGet Azure.Security.KeyVault.SecretsAzure.Security.KeyVault.Secrets

重要

默认情况下,会安装 Azure.Identity 1.1.1,它不支持 Visual Studio Credential。By default Azure.Identity 1.1.1 is installed, which does not support Visual Studio Credential. 你可以使用 Visual Studio Credential 手动将包引用更新为 1.2+。You can update package reference manually to 1.2+ use Visual Studio Credential.

为 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.

后续步骤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 进行身份验证分配 Key Vault 访问策略See How to Authenticate to Key Vault and Assign a Key Vault access policy.

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