This article will discuss about how to connect and use Azure Key Vault in your ASP.NET MVC application.
Azure Key Vault - Provisioning and Configuration
To do this first you need to create an Azure Key Vault. It is a straight forward process. Login to azure portal, search for Key Vault, and select the Key Vault option.
You need to provide a resource group, unique name and location, similar to most of the Azure resources, and click on
Review + Create. And in the review screen confirm the details and create it.
Next select the Secrets blade and add your app settings and connection strings. You can click on the
Generate/Import button and choose the
Upload options as
Manual. Then configure your app settings and connection strings - keys and values to the Name and Value options. And keep other options as default.
Now you have completed your Key Vault configuration, you can click on Secrets blade and you can see your configured secrets list.
In the next section, you will learn how to connect Visual Studio to Azure Key Vault and access the secret values in the code.
Connecting to Azure Key Vault
To connect to Azure Key Vault from Visual Studio, you need to right click on the project and select Add > Connected Service menu.
From the options, choose
Secure Secrets with Azure Key Vault option.
If you’re not signed in you might need to prompt to sign in to your account. Once you signed in, you can choose your Subscription and Key Vault - by default Visual Studio will prompt you with a new key vault, since you already created on you can select it from the list.
And click on the Add button to add key vault reference to your application. This will add reference of the NuGet package
Microsoft.Configuration.ConfigurationBuilders.Azure to the project. Also it will add some configuration in the
Now the configuration is completed. Now you can use modify your
connectionstrings sections like this, so that the application can read from Azure Key Vault.
And you’re completed the implementation. Now if you run the application, and put a break point on the configuration value, you will be able to see the application is reading from Azure Key Vault instead of the value provided in the configuration file. Here is the sample code -
var textAnalyticsKey = ConfigurationManager.AppSettings["TextAnalyticsKey"];
This way you can connect and use Azure Key Vault in your classic ASP.NET MVC applications. If you’re application is running is using .NET Framework 4.5 or lower version, you might need to upgrade to latest version of .NET Framework. You can use Azure Key Vault for App Service certificates as well.
- Azure Key Vault Developer’s Guide
- Add Key Vault to your web application by using Visual Studio Connected Services
Happy Programming :)