Azure's Key Vault solves a big problem of storing connection strings, passwords and other items with your application. The problem is that using the Key Vault with C# isn't entirely clear on the actual operation.
The Key Vault can be used to store anything you want securely and can be recalled online to be used in your application. While there are firewall rules to lock the service down, that will not be covered here. To learn what can be stored in Key Vault, read this article.
What I wanted was a way to store things like a connection string securely away from my web application. So in this article, I will be covering the secrets section here, but the same process works for Key Vault Certificates and Keys.
Using the Code
The first thing you will need is a Key Vault in Azure. To create the Key Vault, click on the "+ Create Project" in the upper left corner of your portal in https://portal.azure.com.
Give the vault a name, it will have to be unique across all of Azure. I recommend using something long but descriptive like
After clicking save and waiting a few moments, you will see a message that the "
Deployment Succeeded". You are now able to view the empty Key Vault by clicking on Resources - KeyVaultName.
When you click on the Key Vault, along the left side, you will see three items, Keys, Secrets, and Certificates. Click on Secrets.
The last thing you will need to do is register the application for authorization in Azure Active Directory. Click on Azure Active Directory under favorites (or search for it if it doesn't exist). Then, click on App Registrations.
Create a registration for the Key Vault application:
After saving, you will see the Client ID which is actually called "Application ID" in the image below.
Finally, you will need to create a key to access this resource. Click on the Keys link to the right in the above image.
Provide a name and select a length of time for the key. For this example, I will select never expires.
When you click on save, the value of the key will show. MAKE SURE YOU COPY THIS DOWN, IT WILL BE THE ONLY CHANCE YOU HAVE TO DO SO. This is your
And then go back into the key vault and apply the permissions to the secrets store. Search and use the name you created above.
Now you can create a project in Visual Studio. For this example, I'm creating a console application. Add the nuget packages:
You are now ready to store information into the "
Secrets" in Key Vault. Add the constants and modify the
Main() to this:
const string CLIENTSECRET = "XxAg+RRvH0qSrfWmQsP1P3gO9FZ8e7j+8x1foE7ugFc=";
const string CLIENTID = "cd830ebc-213c-4586-9246-db0f3e238e32";
const string BASESECRETURI =
static KeyVaultClient kvc = null;
static void Main(string args)
The first method we are going to create is to create an app token to access the Key Vault.
public static async Task<string> GetToken(string authority, string resource, string scope)
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(CLIENTID, CLIENTSECRET);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
DoVault creates, then reads the secrets:
private static void DoVault()
kvc = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
Console.WriteLine("Press enter after seeing the bundle value show up");
SecretBundle secret = Task.Run( () => kvc.GetSecretAsync(BASESECRETURI +
@"/secrets/" + SECRETNAME)).ConfigureAwait(false).GetAwaiter().GetResult();
For the sake of quickness, the above method will wait for the post back / results of the write. After seeing a good write, you can hit enter and have it read from the Key Vault.
I split out the
writeKeyVault because it makes it easier to read:
private static async void writeKeyVault()
SecretAttributes attribs = new SecretAttributes
Enabled = true
IDictionary<string, string> alltags = new Dictionary<string, string>();
alltags.Add("Test1", "This is a test1 value");
alltags.Add("Test2", "This is a test2 value");
alltags.Add("CanBeAnything", "Including a long encrypted string if you choose");
string TestName = "TestSecret";
string TestValue = "searchValue";
string contentType = "SecretInfo";
SecretBundle bundle = await kvc.SetSecretAsync
(BASESECRETURI, TestName, TestValue, alltags, contentType, attribs);
Console.WriteLine("Bundle:" + bundle.Tags["Test1"].ToString());
When it comes to reading this secret later, you will use the "
TestName" parameter above.
After running the code, let's look at the Azure Key Vault resource.
Click on the newly created secret:
Select the current version and click on the tags to see what was saved:
Points of Interest
There really isn't a lot of magic to this. It was a lot easier than I was thinking it was but there was little to no code out there to demo how this works. I hope this helps you save a little time.