Azure Key Vault is a tool for securely storing and accessing secrets (for more information on Azure Key Vault, please refer to this Microsoft article). In today’s blog, we’ll walk you through the very simple steps required to connect to Azure Key Vault from the Azure Web App.

azure key vault

When third party integration systems need to post data to CRM and cannot support OAuth, we can build a Web App /rest API and deploy in Azure. For this Web App, we can store the connection string that will be used to connect to CRM in Key Vault.

For Web App to connect to Key Vault, simply enable Managed service identity and write a small piece of code, as shown below:

1. Turn on Manage service identity for Azure Web App

  • Go to azure portal ( https://portal.azure.com/ )
  • Open the Web App, click on Managed service identity, and make sure Register with Azure Active Directory is On, as shown in screenshot below. Save your changes.

2. Within the Web App, write code as shown below to retrieve the secret from the Key Vault. Note that in the code, KeyVaultUrl = URL of the Key Vault where the CRM connection string is stored in a secret.

using Microsoft.ApplicationInsights;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Configuration;
using System.Threading.Tasks;

namespace Xrm.WebApp.KeyVault
{
    public static class Helper
    {
        public static async Task<string> GetSecretAsync(string secretName)
        {
            try
            {
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                var secret = await keyVaultClient.GetSecretAsync(ConfigurationManager.AppSettings["KeyVaultUrl"], secretName).ConfigureAwait(false);
                return secret.Value;
            }
            catch(Exception e)
            {
                var ai = new TelemetryClient();
                ai.TrackException(e);
                throw;
            }
        }

    }
}

Believe it or not, that’s all it takes! By connecting to Azure Key Vault from the Azure Web App and building a Web App /rest API to deploy in Azure, we have now stored in Key Vault the connection string that will be used to connect to CRM. It’s a simple but powerful solution.

Happy D365’ing!

Avatar for Joe D365

Joe D365

Joe D365 is a Microsoft Dynamics 365 superhero who runs on pure Dynamics adrenaline. As the face of PowerObjects, Joe D365’s mission is to reveal innovative ways to use Dynamics 365 and bring the application to more businesses and organizations around the world.