microsoft azure

How to save and retrieve secret from Azure KeyVault in C#. Nowadays, I’m using a lot of Azure Functions or other Azure services. In a work place where the digital transformation is in progress to achieve better products, security is one of the important aspects to consider.

As a prerequisite, you have to create an account on Azure if you don’t have one. To use Azure KeyVault, also, you need Active Directory in your subscription.

The scope of this post is to create a simple C# application that reads a value from Azure KeyVault. Very common scenario is to read the configuration for the application or important settings such as private key to access other services or connection strings.

Create a new application in Active Directory

First, to save and retrieve secret from Azure KeyVault in C#, you have to allow your app to access to your KeyVault. Go to Azure Portal, then go to “Azure Active Directory” Section.

Active Directory on Azure
Active Directory on Azure

So, in the “App registrations” section, click on “New application registration”.

Register a new application in Active Directory
Register a new application in Active Directory

When you click on New registration, another section is open where you have to type or select:

  • name of the application (it is relevant only for my memory)
  • what kind of validation you want
  • redirect URI (optional)
Register an application in Active Directory
Register an application in Active Directory

Then, press Register. If the KeyVault is successfully created, you redirect to the overview page. In this page, you find the Application (client) Id: this is the ClientId we have to use in the configuration of the KeyVaultClient in the C# application.

Application Id for the application
Application Id for the application

Allow the application to access to KeyVault

So, I have to create a ClientSecret for my application. Click on Certificates & secrets, then add a New client secret click on the button (see the image below).

Certificates & secrets for the application
Certificates & secrets for the application

So, when you click on New client secret, a new window is opened with title “Add a client secret“. Here I can add a description and for how long I have to keep this client secret active. For test purpose, I choose Never.

Add a client secret
Add a client secret

Now, press the Add button. If the client secret is successfully created, you can see in the list of client secrets, a new one. Copy immediately this value because you won’t see or copy it again.

Client secret for the application
Client secret for the application

You have to copy it immediately because it will be shown only once, it means that you will not able to see it again next time.

So, the last step is to allow this application to access to the KeyVault. For that, return to the KeyVault page and click Access policies on the left menu.

Access policy to allow the application to access to the keyvault
Access policy to allow the application to access to the keyvault

Then, click on Add Access Policy. In a new section I can choose different options:

  • Configure from template (optional) but I choose Key, Secret & Certificate Management
  • Key permissions
  • Secret permissions
  • Certificate permissions
  • Select principal

Therefore, in the dropdown I leave the default options. For Select principal I have to search and add the application (in this case key-vault-test).

Add access policy
Add access policy

So, Click the Select button, the Add. I see the Access policies page and in the application list the app. Remember to Save, click on the button on the top.

Create a C# application

The goal of our post is to save and retrieve secret from Azure KeyVault in C#. First, create a new Console Application with .NET Core 3. Add 2 Nuget packages:

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

Finally, I have everything to create my KeyVault client. This is the code:

var _keyVaultClient = new KeyVaultClient(
    async (string authority, string resource, string scope) =>
{
    var authContext = new AuthenticationContext(authority);
    var clientCred = new ClientCredential(clientId, clientSecret);
    var result = await authContext.AcquireTokenAsync(resource, clientCred);
    return result.AccessToken;
});

Now, a client for the KeyVault is set up but I don’t have keys there. Then, I want to create a secret from my code in the KeyVault. Simple like that.

_keyVaultClient.SetSecretAsync(url, "Password", "This is my password");
In the Azure Portal I can see all my Secrets
In the Azure Portal I can see all my Secrets

After that, the Password secret was created from my code (the other keys are other tests). For each secret, you can see how many versions there are and add a new version. If you click on one version in the list, we see all details of this secret. If you have the permissions, also you can see the secret.

A secret in KeyVault
A secret in KeyVault

It is time to retrieve the secret.

var pwd = _keyVaultClient.GetSecretAsync(url, "Password").GetAwaiter().GetResult();
Console.WriteLine($"The secret passowrd is: {pwd.Value}");

For more documentation about Azure KeyVault, Microsoft has a lot of documentation.

Complete source code

using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static string clientId = "<your clientId>";
        static string clientSecret = "<your client secret>";
        static string url = "https://azuks-keyvault-q001.vault.azure.net/";

        static void Main(string[] args)
        {
            var _keyVaultClient = new KeyVaultClient(
                async (string authority, string resource, string scope) =>
            {
                var authContext = new AuthenticationContext(authority);
                var clientCred = new ClientCredential(clientId, clientSecret);
                var result = await authContext.AcquireTokenAsync(resource, clientCred);
                return result.AccessToken;
            });

            _keyVaultClient.SetSecretAsync(url, "Password", "This is my password");

            var pwd = _keyVaultClient.GetSecretAsync(url, "Password").GetAwaiter().GetResult();
            Console.WriteLine($"The secret passowrd is: {pwd.Value}");
        }
    }
}

Quite a lot of steps but at the end we can save and retrieve secret from Azure KeyVault in C#.

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: