Tag Archives: Managed Identity in Visual Studio

Using Managed Identity With Azure KeyVault

One of the things that’s always irked me about Azure KeyVault is that, whilst it may indeed be a super secure store of information, ultimately, you need some way to access it – which means that you’ve essentially moved the security problem, rather than solved it.

However, after speaking to a colleague at work, I’ve been playing with the concept of using a Managed Identity for authentication. This does go some way to alleviate my concerns for interactive security. To be clear, my concerns are less that the system is less secure, but that because you’ve simply moved the keys to the castle, that you’re just not getting sufficient benefit for the added complexity.

Anyway, this post covers using Managed Identity to authenticate KeyVault locally with Visual Studio.

Install the config package

The first step is to install the NuGet package. This post is based on .Net Core 3.1; however, I believe that it’s the same for 5.0.

Install-Package Microsoft.Extensions.Configuration.AzureKeyVault

Change the CreateHostBuilder

In Program.cs, edit CreateHostBuilder:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var configRoot = config.Build();

                    config.AddUserSecrets<Program>();

                    var azureServiceTokenProvider = new AzureServiceTokenProvider();
                    var keyVaultClient = new KeyVaultClient(
                        new KeyVaultClient.AuthenticationCallback(
                            azureServiceTokenProvider.KeyVaultTokenCallback));

                    config.AddAzureKeyVault(
                        $"https://{configRoot["KeyVaultName"]}.vault.azure.net/",
                        keyVaultClient,
                        new DefaultKeyVaultSecretManager());
                });

You’ll need to add the key vault name either in your appsettings.json, or you could keep it in a secrets file (although I don’t see why you would want to hide this). For example:

  "KeyVaultName": "my-keyvault"

Visual Studio Credentials

Finally, set your local credentials in Visual Studio:

Now you can simply read from the config, and it will pull the value from the KeyVault where it needs to:

myValue = Configuration.GetValue<string>("key-vault-secret");

References

https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-5.0