top of page

Integrating Azure Key Vault with .NET Web Apps and Function Apps

Azure Key Vault is a cloud service that provides secure storage to store your keys, secrets, and other sensitive configuration data for your application. Most of the time these keys are stored in the application configuration file such as appsetting.json, web.config in a .NET application. You can have multiple versions of the same key securely stored here and you can use the same vault for the secrets used in different apps. Storing Application secrets in Azure Key Vault

Go to the Azure portal and create a new Key Vault by clicking on Create a resource tile.

Create resource

Key Vault

Create key vault


Once you have successfully provisioned your Key Vault Create a secret by going to the Secrets tab.


Create secret


Once you have created the secret you will have the Secret Identifier which will be used for retrieving secrets for a function app later in this article.

Authorize your application to use Key vault secret

Next, you need to authorize the application to use the required secret.

There are mainly two ways to authorize applications in Key Vault secrets.


  1. Using Azure Active Directory App

  2. Using Managed Identity

1. Using Azure Active Directory App

This method is mainly used when you need to access your key vault secrets in addition to Azure resources. (from your local machine)

Here you have to create an Azure Active Directory app. Go to the Portal > Azure Active Directory > App registration blade > New Registration. Register your AAD App with your needed configurations.

AAD App registration


After the registration and copy the Application (Client) ID for a text editor from the Overview page.

AAD App overview


Create a new client secret and copy its Value as well to a text editor. You will need these values to add to the application.json file in your dot net core project

Create Secret


Then you should go to your Key vault > Access policies blade and Add Access policy with your AAD app using your copied Client ID and necessary permissions.

Add Access policy


2. Using Managed Identity

This method is mainly used when you need to access your key vault secrets from Azure resources. (production env such as azure web apps)

To enable identity you should go to your App service > Identity and Turn On the Status and copy the Object(Principal ID).

Managed Identity


Then you should go to your Key vault > Access policies blade and Add Access policy with your Azure resource using copied Principal ID and necessary permissions as in the previous step.

Using Key Vault secrets in your ASP .NET app

Now let's try to retrieve the secret we created in the Azure Key Vault.

First of all, to connect with the Azure key vault you need to install the below NuGet packages. Use the Package manager console in Visual studio to install those.

PM> Install-Package Microsoft.Extensions.Configuration.AzureKeyVault
PM> Install-Package Azure.Identity
PM> Install-Package Azure.Security.KeyVault.Secrets

Now we need to update CreateHostBuilder method in Program.cs to plug Azure Key Vault into ASP .NET Core Application configurations.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)        
        .ConfigureAppConfiguration((context, config) =>        
        {
            var settings = config.Build();
            
            if (!context.HostingEnvironment.IsDevelopment())            
            {
                // Production Env
                // Connect to Azure Key Vault using the Managed Identity.
                var keyVaultEndpoint = settings["AzureKeyVaultEndpoint"];
                
                if (!string.IsNullOrEmpty(keyVaultEndpoint))                
                {
                    var azureServiceTokenProvider = new 
                                        AzureServiceTokenProvider();
                    var keyVaultClient = new KeyVaultClient(new 
                        KeyVaultClient.AuthenticationCallback                             
                       (azureServiceTokenProvider.KeyVaultTokenCallback));
                    config.AddAzureKeyVault(
                        keyVaultEndpoint, 
                        keyVaultClient, 
                        new DefaultKeyVaultSecretManager());                
                }            
            }
            else            
            {
                // Development Env
                // Connect to Azure Key Vault using the Azure AD App
                
                var keyVaultEndpoint = settings["AzureKeyVault:Endpoint"];
                var keyVaultClientId = settings["AzureKeyVault:ClientId"];
                var keyVaultClientSecret = settings["AzureKeyVault:ClientSecret"];
                
                if (!string.IsNullOrEmpty(keyVaultEndpoint) && 
                    !string.IsNullOrEmpty(keyVaultClientId) && 
                    !string.IsNullOrEmpty(keyVaultClientSecret))                
                {
                    config.AddAzureKeyVault(
                        keyVaultEndpoint, 
                        keyVaultClientId, 
                        keyVaultClientSecret, 
                        new DefaultKeyVaultSecretManager());                
                }            
            }        
        })        
        .ConfigureWebHostDefaults(webBuilder=>        
        {
            webBuilder.UseStartup<Startup>();        
        });

Here we have two options, For the Development Environment in your local machine, we are using an AAD App to access the token. When the application is deployed to Azure App Service we can use managed Identity to access the Azure Key Vault. For that, we need to update the appsettings.json file as well.

{
    "Logging": 
    {
        "LogLevel": 
        {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"    
        }  
    },
    "AllowedHosts": "*",
    // Production Env
    
    "AzureKeyVaultEndpoint": "[Your_AzureKeyVaultURI]",
    // Development Env
    
    "AzureKeyVault": 
    {
        "Endpoint": "[Your_AzureKeyVaultURI]",
        "ClientId": "[Your_AAD_APP_ClientId]",
        "ClientSecret": "[Your_AAD_APP_Secret]"  
    },
    "FUNCTION_APP_URL": "[Your_functionapp_url]"
}

Now you have access to the Key vault secrets via application configurations as a separate configuration source. You can access the created secret using constructor injected configuration as below

public TodoDbContext(IConfiguration config)
{
    _config=config;
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
   if (!optionsBuilder.IsConfigured)    
   {
       optionsBuilder.UseSqlServer(_config["DbConnString"]);    
   }
      
   base.OnConfiguring(optionsBuilder);
}

private IConfiguration _config;

When you deploy your app to the Azure App Service you can use your App service Configuration to change the Azure key vault URI (Endpoint) using Application settings.



Using Key Vault secrets in your Function app

Since there is no appsetting.json used in function apps we can use Azure function app configuration to access the key vault. You may initialize the properties as below.

private static string _storageKey = Environment.GetEnvironmentVariable(“StorageKey”, EnvironmentVariableTarget.Process);

Once you have published your function app to Azure go to the Function app instance > Configuration and add an application setting.

Name:  StorageKey
Value: @Microsoft.KeyVault(SecretUri=[Your_key_vault_secret_identifier])

You can find the Key vault secret identifier in Secert Version page in your Azure key vault inside Secrets blade.

Key Vault Secret


Finally, you need to add the Identity of the Function App to your Key Vault as we did previously in App service configuration (refer to Image: Managed Identity)



Source: Medium - Dumindu De Silva


The Tech Platform

bottom of page