Azure Key Vault Config Builder in 4.7.1

倖福魔咒の 提交于 2021-02-07 09:46:45

问题


We can't go to .net core yet in my company. I'm trying to investigate how to best use the azure key vault to store configuration items for our api app services.

I have a simple webapi project with this global.asax file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.WebHost;
using System.Web.Routing;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;

namespace kv.api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            LoadAzureKeyVaultSettings();
        }


        protected void LoadAzureKeyVaultSettings()
        {
            var tokenProvider = new AzureServiceTokenProvider("RunAs=CurrentUser;");

            var kvClient = new KeyVaultClient((authority, resource, scope) => tokenProvider.KeyVaultTokenCallback(authority, resource, scope));

            var builder = new ConfigurationBuilder()
                .AddAzureKeyVault("https://mykvurihere.vault.azure.net/", kvClient, new DefaultKeyVaultSecretManager());

            builder.Build();
        }
    }

}

Then i have a simple webapi endpoint here:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using kv.api.Models;

namespace kv.api.Controllers
{
    public class SettingsController : ApiController
    {
        /// <summary>
        /// Method that returns all the keys out of the Configuration Manager's App Settings.  Can use this endpoint to test KeyVault integrations.
        /// </summary>
        /// <returns>List of Settings</returns>
        public IEnumerable<Setting> GetAllSettings()
        {
            var settings = ConfigurationManager.AppSettings.AllKeys
                .Select(key => new Setting()
                {
                    Key = key,
                    Value = ConfigurationManager.AppSettings[key]
                })
                .ToList();

            return settings;
        }
    }
}

It compiles, I get no runtime exception, but this endpoint isn't yielding my configs from the key vault (I do get the appSettings defined in my web.config). What am I missing here?

--- UPDATE It appears that the key vault metrics reported in the azure portal are showing that my app is successfully retrieving the secrets, but they are not being added to the app's AppSettings...

Thanks!


回答1:


I did my fair share of figuring this one out so I decided to write a quite lengthy blog post about it which you can find here.

In a nutshell, in my opinion the best way to integrate the Key Vault config builder is not through .NET code, but simply by adding Key Vault as a connected service, then set it up in your Web.config, like this:

<configuration>
  <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="your vault's name" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=1.0.0.0, Culture=neutral" />
    </builders>
  </configBuilders>
  <appSettings configBuilders="AzureKeyVault">
    <add key="MyValue" value="Value from Web.config" />
  </appSettings>
  ...
</configuration>

Then if you set up authentication properly between your Key Vault and your app, add a secret to your Key Vault with the name of "MyValue", it will be replaced at runtime and you will be able to access the secret from Key Vault in your application like this:

ConfigurationManager.AppSettings["MyValue"]



回答2:


I found a solution but it seems really wonky... Posting it here to get feedback. What I ended up doing is manually setting key/values in the ConfigurationManager.AppSettings collection like so:

using System.Configuration;
using System.Web.Http;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;

namespace kv.api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            LoadAzureKeyVaultSettings();
        }


        protected void LoadAzureKeyVaultSettings()
        {
           var tokenProvider = new AzureServiceTokenProvider(ConfigurationManager.AppSettings["AzureServiceTokenProviderConnectionString"]);

           var kvClient =  new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback));

            var builder = new ConfigurationBuilder()
                .AddAzureKeyVault("https://mykvurihere.vault.azure.net/", kvClient,
                    new DefaultKeyVaultSecretManager());

           var config = builder.Build();

           foreach (var keyValuePair in config.AsEnumerable())
           {
               ConfigurationManager.AppSettings.Set(keyValuePair.Key, keyValuePair.Value);
           }  
        }
    }
}


来源:https://stackoverflow.com/questions/53746290/azure-key-vault-config-builder-in-4-7-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!