Reading secrets from KeyVault in your Azure Web App

KeyVaultPlusAzureWebAppAzure KeyVault is a great Azure offerring that allows you to store for example secrets or certificates. You are currently looking at the first post out of a series of posts on how to grab secrets or certificates from KeyVault in your web applications. This post wil focus on creating the KeyVault, giving access to you Azure Web App and retrieving a secret in two different ways. I will be using an ASP.NET full framework app in this demo but this will work for .NET Core as well.

Create the KeyVault and Web App using an ARM template

When you want to create a resource in Azure there are multiple ways to do that. I prefer ARM templates over the portal or the Azure CLI. So, in this post you will see ARM templates. Our web app will authenticate to KeyVault using a managed Identity that we will enable in the template.

First, we need a KeyVault to store our secrets. Here’s the template to create a KeyVault and add a secret to it named ‘secret’.

Now we need to deploy our web app. Here’s the template to do that. It will create the web app and enable the system-assigned managed identity. To allow this app access to the secrets in KeyVault, we will need to assign an access policy. That is done in the last resource in this template.

Reading a secret in your app

There are multiple ways to read a secret from KeyVault in your app. I’ll show you two.


The first one will use a few lines of code to read the secret we created earlier. This might come in handy when you have your own way of loading configuration instead of the default app settings in the web.config. Here is an example:

To connect with the KeyVault, this code will use the ‘AzureServiceTokenProvider’ to get you a valid access token. When you run this code in your Azure Web App, it will use the apps Managed Identity. When you debug locally, you need to be signed in with your Azure subscription. Use ‘Az login’ to do so. For this to work you must make sure that your account has the ‘Get’ and ‘List’ access policy on the KeyVault like we assigned to our Managed Identity in the ARM template.

KeyVault Config Builder

Since version 4.7.1 of the .NET Framework and .NET Core 2.0 you have the ability to use config builders. This is a mechanism to get config from external resources. One of the available config builder is the one for KeyVault.

We first need to install a NuGet package:

Now we need to add the following section to our web.config above your app settings.

The last step is to edit your appSettings to look like mine; add ‘configBuilders=”Secrets”‘ and add the name of your secret with a dummy value:

Now read this setting like it was a normal setting you would read from your appSettings:


You may also like...