安全地保存 Web 应用的密钥应用程序设置Securely save secret application settings for a web application

概述Overview

本文介绍如何安全地保存 Azure 应用程序的密钥应用程序配置设置。This article describes how to securely save secret application configuration settings for Azure applications.

传统上,所有 Web 应用配置设置都保存在配置文件(如 Web.config)中。这一做法会导致将密钥设置(如云凭据)签入到公共源代码管理系统(如 GitHub)中。Traditionally all web application configuration settings are saved in configuration files such as Web.config. This practice leads to checking in secret settings such as Cloud credentials to public source control systems like GitHub. 同时,因为更改源代码和重新配置开发设置都需要开销,因此会难以遵循安全最佳实践。Meanwhile, it could be hard to follow security best practice because of the overhead required to change source code and reconfigure development settings.

为了确保开发过程的安全性,创建了工具和框架库,以安全地保存应用程序机密设置,并最大程度地减少对源代码的更改或不对其进行更改。To make sure the development process is secure, tooling and framework libraries are created to save application secret settings securely with minimal or no source code change.

ASP.NET 和 .NET Core 应用程序ASP.NET and .NET Core applications

将密钥设置保存在源代码管理文件夹外部的用户密钥存储中。Save secret settings in User Secret store that is outside of source control folder

如果你正在快速建立原型或无法访问 Internet,请先将源代码管理文件夹外部的密钥设置移动到用户密钥存储。If you are doing a quick prototype or you don't have internet access, start with moving your secret settings outside of source control folder to User Secret store. 用户密钥存储是保存在用户探查器文件夹下的一个文件,因此密钥不会签入到源代码管理。User Secret store is a file saved under user profiler folder, so secrets are not checked in to source control. 下图演示了用户密钥的工作原理。The following diagram demonstrates how User Secret works.

用户密钥将密钥设置保持在源代码管理外部

如果正在运行 .NET Core 控制台应用程序,请使用密钥保管库来安全地保存你的密钥。If you are running .NET core console application, use Key Vault to save your secret securely.

在 Azure 密钥保管库中保存密钥设置Save secret settings in Azure Key Vault

如果正在开发一个项目,并需要安全地共享源代码,请使用 Azure Key VaultIf you are developing a project and need to share source code securely, use Azure Key Vault.

  1. 在 Azure 订阅中创建密钥保管库。Create a Key Vault in your Azure subscription. 填写 UI 上的所有必填字段,然后单击边栏选项卡底部的“创建” Fill out all required fields on the UI and click Create on the bottom of the blade

    创建 Azure Key Vault

  2. 授予你和团队成员访问密钥保管库的权限。Grant you and your team members access to the Key Vault. 如果你的团队规模较大,可以创建 Azure Active Directory 组并将该安全组访问权限添加到密钥保管库。If you have a large team, you can create an Azure Active Directory group and add that security group access to the Key Vault. 在“密钥权限” 下拉列表中,检查“密钥管理操作” 下的“获取” 和“列表” 。In the Secret Permissions dropdown, check Get and List under Secret Management Operations. 如果已创建 Web 应用,请向 Web 应用授予对 Key Vault 的访问权限,以便它可以访问密钥保管库,而无需在应用设置或文件中存储机密配置。If you already have your web app created, grant the web app access to the Key Vault so it can access the key vault without storing secret configuration in App Settings or files. 按名称搜索 Web 应用,并以向用户授予访问权限的相同方式添加该应用。Search for your web app by its name and add it the same way you grant users access.

    添加密钥保管库访问策略

  3. 在 Azure 门户中将机密添加到 Key Vault。Add your secret to Key Vault on the Azure portal. 对于嵌套的配置设置,请将“:”替换为“--”,以使密钥保管库密钥名称有效。For nested configuration settings, replace ':' with '--' so the Key Vault secret name is valid. 不能在密钥保管库密钥的名称中使用“:”。':' is not allowed to be in the name of a Key Vault secret.

    添加密钥保管库密钥

    备注

    在 Visual Studio 2017 V15.6 之前,我们曾建议安装 Visual Studio 的 Azure 服务身份验证扩展。Prior to Visual Studio 2017 V15.6 we used to recommend installing the Azure Services Authentication extension for Visual Studio. 但是现在该扩展已弃用,因为它的功能已集成在 Visual Studio 中。But it is deprecated now as the functionality is integrated within the Visual Studio . 因此,如果你使用的是旧版本的 Visual Studio 2017,我们建议你更新至至少 VS 2017 15.6 或更高版本,以便可以本机使用此功能并使用 Visual Studio 登录标识本身访问密钥保管库。Hence if you are on an older version of visual Studio 2017 , we suggest you to update to at least VS 2017 15.6 or up so that you can use this functionality natively and access the Key-vault from using the Visual Studio sign-in Identity itself.

  4. 将以下 NuGet 包添加到项目:Add the following NuGet packages to your project:

    Microsoft.Azure.KeyVault
    Microsoft.Azure.Services.AppAuthentication
    Microsoft.Extensions.Configuration.AzureKeyVault
    
  5. 将以下代码添加到 Program.cs 文件:Add the following code to Program.cs file:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
             Host.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());
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    
        private static string GetKeyVaultEndpoint() => Environment.GetEnvironmentVariable("KEYVAULT_ENDPOINT");
    
  6. 将密钥保管库 URL 添加到 launchsettings.json 文件。Add your Key Vault URL to launchsettings.json file. 环境变量名称 KEYVAULT_ENDPOINT 将在步骤 6 添加的代码中进行定义 。The environment variable name KEYVAULT_ENDPOINT is defined in the code you added in step 6.

    将密钥保管库 URL 添加为项目环境变量

  7. 开始调试项目。Start debugging the project. 它应已成功运行。It should run successfully.

ASP.NET 和 .NET 应用程序ASP.NET and .NET applications

.NET 4.7.1 支持密钥保管库和密钥配置生成器,这可以确保在不更改代码的情况下将密钥移动到源代码管理文件夹的外部。.NET 4.7.1 supports Key Vault and Secret configuration builders, which ensures secrets can be moved outside of source control folder without code changes. 若要继续,请下载 .NET 4.7.1,如果应用程序使用的是较旧版本的 .NET Framework,则将其进行迁移。To proceed, download .NET 4.7.1 and migrate your application if it's using an older version of .NET framework.

将密钥设置保存在源代码管理文件夹外部的密钥文件中。Save secret settings in a secret file that is outside of source control folder

如果正在快速编写原型,且不想预配 Azure 资源,请使用此选项。If you are writing a quick prototype and don't want to provision Azure resources, go with this option.

  1. 将以下 NuGet 包安装到你的项目Install the following NuGet package to your project

    Microsoft.Configuration.ConfigurationBuilders.Base
    
  2. 创建一个类似于以下内容的文件。Create a file that's similar to the following. 将其保存在你的项目文件夹外部的某个位置下。Save it under a location outside of your project folder.

    <root>
        <secrets ver="1.0">
            <secret name="secret1" value="foo_one" />
            <secret name="secret2" value="foo_two" />
        </secrets>
    </root>
    
  3. 将密钥文件定义为 Web.config 文件中的配置生成器。Define the secret file to be a configuration builder in your Web.config file. 将该部分置于 appSettings 部分前。Put this section before appSettings section.

    <configBuilders>
        <builders>
            <add name="Secrets"
                 secretsFile="C:\Users\AppData\MyWebApplication1\secret.xml" type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder,
                    Microsoft.Configuration.ConfigurationBuilders, Version=1.0.0.0, Culture=neutral" />
        </builders>
    </configBuilders>
    
  4. 指定 appSettings 部分使用密钥配置生成器。Specify appSettings section is using the secret configuration builder. 确保有含有虚拟值的机密设置的条目。Make sure there is an entry for the secret setting with a dummy value.

        <appSettings configBuilders="Secrets">
            <add key="webpages:Version" value="3.0.0.0" />
            <add key="webpages:Enabled" value="false" />
            <add key="ClientValidationEnabled" value="true" />
            <add key="UnobtrusiveJavaScriptEnabled" value="true" />
            <add key="secret" value="" />
        </appSettings>
    
  5. 调试应用。Debug your app. 它应已成功运行。It should run successfully.

在 Azure Key Vault 中保存密钥设置Save secret settings in an Azure Key Vault

按照 ASP.NET Core 部分中的说明为你的项目配置密钥保管库。Follow instructions from ASP.NET core section to configure a Key Vault for your project.

  1. 将以下 NuGet 包安装到你的项目Install the following NuGet package to your project

    Microsoft.Configuration.ConfigurationBuilders.UserSecrets
    
  2. 定义 Web.config 中的密钥保管库配置生成器。将该部分置于 appSettings 部分前。Define Key Vault configuration builder in Web.config. Put this section before appSettings section. 如果密钥保管库位于公共 Azure 中,则将 vaultName 替换为密钥保管库名称,如果正在使用 Sovereign 云,则将其替换为完整的 URI。Replace vaultName to be the Key Vault name if your Key Vault is in public Azure, or full URI if you are using Sovereign cloud.

    <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="Test911" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, ConfigurationBuilders, Version=1.0.0.0, Culture=neutral" />
        </builders>
    </configBuilders>
    
  3. 指定 appSettings 部分使用密钥保管库配置生成器。Specify appSettings section is using the Key Vault configuration builder. 确保有任何含有虚拟值的密钥设置的条目。Make sure there is any entry for the secret setting with a dummy value.

    <appSettings configBuilders="AzureKeyVault">
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <add key="secret" value="" />
    </appSettings>
    
  4. 开始调试项目。Start debugging the project. 它应已成功运行。It should run successfully.