Click here to Skip to main content
14,035,489 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.8K views
5 bookmarked
Posted 13 Apr 2019
Licenced CPOL

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

, 13 Apr 2019
Rate this:
Please Sign up or sign in to vote.
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.

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

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

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:

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.

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:

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:

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.

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.

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)

Share

About the Author

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

You may also be interested in...

Pro

Comments and Discussions

 
QuestionSecrets Pin
sterenas13-Apr-19 6:59
membersterenas13-Apr-19 6:59 
AnswerRe: Secrets Pin
SEJohnson13-Apr-19 15:44
memberSEJohnson13-Apr-19 15:44 
GeneralRe: Secrets Pin
SEJohnson13-Apr-19 15:47
memberSEJohnson13-Apr-19 15:47 
QuestionSorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 2:52
memberSEJohnson13-Apr-19 2:52 
AnswerRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 4:43
protectorOriginalGriff13-Apr-19 4:43 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:06
memberSEJohnson13-Apr-19 5:06 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:06
memberSEJohnson13-Apr-19 5:06 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 5:18
protectorOriginalGriff13-Apr-19 5:18 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
SEJohnson13-Apr-19 5:19
memberSEJohnson13-Apr-19 5:19 
GeneralRe: Sorry pictures seem to have vanished after publication. Pin
OriginalGriff13-Apr-19 5:36
protectorOriginalGriff13-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
memberSEJohnson15-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190424.1 | Last Updated 13 Apr 2019
Article Copyright 2019 by SEJohnson
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid