在 Azure Key Vault 中存储 SQL 个数据库连接字符串

Storing SQL Database Connection Strings in Azure Key Vault

我正在将应用程序机密从源控制 web.config(使用转换)移动到 Azure Key Vault 机密。这对密码之类的东西很有效,但是 SQL 数据库连接字符串似乎很难移出 web.config。 web.config 中其他地方有各种对连接字符串的引用(例如角色提供程序、成员资格提供程序、配置文件提供程序、entity framework 等)。

是否有任何模式和最佳做法可以帮助完成此迁移?我打算使用连接字符串名称作为秘密名称,使用连接字符串值作为秘密值。但是,我不确定如何处理连接字符串提供程序名称。

此外,理想情况下,只有密钥保管库 URL 会在 web.config 中,但是 web.config 中的现有配置如果当前正在引用,如何与密钥保管库集成一个实际的连接字符串。

IIS 托管的 ASP.NET 应用程序目前 运行 在 Azure 虚拟机中,但也必须考虑本地开发。

更新 其他 libraries/packages 添加和使用的如下配置怎么样?

<sessionState mode="InProc" customProvider="DefaultSessionProvider">
  <providers>
    <add name="DefaultSessionProvider"
         type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
         connectionStringName="DefaultConnection" />
  </providers>
</sessionState>
<profile defaultProvider="DefaultProfileProvider">
  <providers>
    <add name="DefaultProfileProvider"
         type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
         connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
  <providers>
    <add name="DefaultMembershipProvider"
         type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
         connectionStringName="DefaultConnection" enablePasswordRetrieval="false"
         enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
  <providers>
    <add name="DefaultRoleProvider"
         type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
         connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</roleManager>

想出了一个解决方案:将连接字符串保留在 web.config 中,因为它们被 web.config 的其他部分引用,但在应用程序启动时更新值。

protected void Application_Start()
{
    /* ... */

    var configurationReadOnlyField = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

    var connection = ConfigurationManager.ConnectionStrings[connectionName];
    s_configurationReadOnlyField.SetValue(connection, false);

    connection.ConnectionString = newValue;

    /* ... */
}