Click here to Skip to main content
15,885,925 members
Articles / Hosted Services / Azure
Tip/Trick

Using C# .NET to Read and Write from Azure Key Vault Secrets

Rate me:
Please Sign up or sign in to vote.
4.47/5 (5 votes)
13 Apr 2019CPOL3 min read 89.6K   11   14
How to use C#.NET to read and write from Azure key vault secrets

Introduction

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.

Background

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.

Image 1

Give the vault a name, it will have to be unique across all of Azure. I recommend using something long but descriptive like KeyVaultAppName.

Image 2

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.

Image 3

When you click on the Key Vault, along the left side, you will see three items, Keys, Secrets, and Certificates. Click on Secrets.

Image 4

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.

Image 5

Create a registration for the Key Vault application:

Image 6

After saving, you will see the Client ID which is actually called "Application ID" in the image below.

Image 7

Finally, you will need to create a key to access this resource. Click on the Keys link to the right in the above image.

Image 8

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 ClientSecret.

And then go back into the key vault and apply the permissions to the secrets store. Search and use the name you created above.

Image 9

Now you can create a project in Visual Studio. For this example, I'm creating a console application. Add the nuget packages:

  • Microsoft.Azure.KeyVault
  • Microsoft.Azure.Management.KeyVault
  • Microsoft.IdentityModel.Clients.ActiveDirectory

You are now ready to store information into the "Secrets" in Key Vault. Add the constants and modify the Main() to this:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

const string CLIENTSECRET = "XxAg+RRvH0qSrfWmQsP1P3gO9FZ8e7j+8x1foE7ugFc="; 
const string CLIENTID = "cd830ebc-213c-4586-9246-db0f3e238e32";
const string BASESECRETURI = 
    "https://testvaultcp.vault.azure.net"; // available from the Key Vault resource page

static KeyVaultClient kvc = null;

static void Main(string[] args)
{
    DoVault();

    Console.ReadLine();
}

The first method we are going to create is to create an app token to access the Key Vault.

C#
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");

      return result.AccessToken;
}

The DoVault creates, then reads the secrets:

C#
private static void DoVault()
{
     kvc = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));

     // write
     writeKeyVault();
     Console.WriteLine("Press enter after seeing the bundle value show up");
     Console.ReadLine();

     SecretBundle secret = Task.Run( () => kvc.GetSecretAsync(BASESECRETURI + 
          @"/secrets/" + SECRETNAME)).ConfigureAwait(false).GetAwaiter().GetResult();
     Console.WriteLine(secret.Tags["Test1"].ToString());
     Console.WriteLine(secret.Tags["Test2"].ToString());
     Console.WriteLine(secret.Tags["CanBeAnything"].ToString());

     Console.ReadLine();

}

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:

C#
private static async void writeKeyVault()// string szPFX, string szCER, string szPassword)
{
     SecretAttributes attribs = new SecretAttributes
     {
          Enabled = true//,
          //Expires = DateTime.UtcNow.AddYears(2), // if you want to expire the info
          //NotBefore = DateTime.UtcNow.AddDays(1) // if you want the info to 
                                                   // start being available later
     };

     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"; // this is what you will use to search for the item later
     string contentType = "SecretInfo"; // whatever you want to categorize it by; you name it

     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.

Image 10

Click on the newly created secret:

Image 11

Select the current version and click on the tags to see what was saved:

Image 12

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.

History

  • 4/12/2019: Original post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect NetProf, Inc
United States United States
Programming since 1977 (8 years old) Started on the commodore pet (Basic and Assembly) and progressed through the Atari 400/800, Apple II/e/c, PC DOS (Pascal, C, C++, Assembly). Computers have been a passion my entire life.

During my early pre-business years I wrote two BBS systems and a MUD from scratch, a few BBS doors, and managed code from a custom circle MUD.

I've been in the computer industry for over 30 years in computer programming, networking, servers and security where I'm well known in the industry after catching numerous hackers and their subsequent prosecution.

Currently I use C#, Angular, jQuery, and JavaScript. Creating server services, background processing, web services, and data exchanges.

But have also used C/C++, VB, VBscript, PHP, and Powershell in Windows and Linux and MSSQL, MySQL, or Postgres. I've been spending a lot of time in Azure as well.

I still consult but I'm working more as an entrepreneur now creating businesses with technology and helping others realize their ideas where they lack the technical experience to bring their idea to fruition.

My current project is a security product that automates security in an active directory environment for businesses and education including IDM, SSO, and a self-services web portal.

Outside of technology I love aviation and am a private pilot.

Comments and Discussions

 
QuestionConnect Azure Key vault with On-Prem asp.net mvc application Pin
Member 1624622918-Apr-24 2:34
Member 1624622918-Apr-24 2:34 
QuestionSecrets Pin
sterenas13-Apr-19 6:59
sterenas13-Apr-19 6:59 
AnswerRe: Secrets Pin
SEJohnson13-Apr-19 15:44
SEJohnson13-Apr-19 15:44 
GeneralRe: Secrets Pin
SEJohnson13-Apr-19 15:47
SEJohnson13-Apr-19 15:47 
QuestionSorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 2:52
SEJohnson13-Apr-19 2:52 
AnswerRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 4:43
mveOriginalGriff13-Apr-19 4:43 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:06
SEJohnson13-Apr-19 5:06 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:06
SEJohnson13-Apr-19 5:06 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 5:18
mveOriginalGriff13-Apr-19 5:18 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:19
SEJohnson13-Apr-19 5:19 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 5:36
mveOriginalGriff13-Apr-19 5:36 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
Sean Ewington15-Apr-19 4:37
staffSean Ewington15-Apr-19 4:37 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson15-Apr-19 4:38
SEJohnson15-Apr-19 4:38 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
Sean Ewington15-Apr-19 4:40
staffSean Ewington15-Apr-19 4:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.