How to read Azure KeyVault secrets using Managed Identity in .NET Framework 4.8 C#

Using Managed Identity to deploy azure resources is considered best practice as it reduces the overhead of keeping additional credentials (tokens/passwords) in config files. This article is about accessing Auzre KeyVault using Managed Identity. I am using .NET Framework 4.8 version for this tutorial.

Step 1 – Create KeyVault and secrets

First, just go to Azure Portal and create necessary secret values for testing. I would go with a “testkey” and a dummy value.

(I am assuming you know the basics of Azure Portal and knows how to create an azure resource such as KeyVault)

image

Also, please take a note of the “Vault URI” you can see in the “Overview” section. We would require it in the C# Code.

Step 2 – Create Sample .NET App

Next, open Visual Studio (I have used 2022) and start a new project. I have used a .NET Framework 4.8 Console Application.

Step 3 – Install necessary NuGet packages

We require two major packages for this project. Install these:

1. Azure.Identity
2. Azure.Security.KeyVault.Secrets

image

Step 4 – Coding!

This is the sample code I have used. Make sure to replace with your keyvault URL.

using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

namespace kvtest
{
     internal class Program
     {
         static void Main(string[] args)
         {
             SecretClient secretClient = new SecretClient(new Uri("https://your-keyvault.vault.azure.net/"), new DefaultAzureCredential());
             var secret = secretClient.GetSecret("testkey");
             Console.WriteLine(secret.Value.Value);

            Console.ReadKey();

        }
     }
}

Notice the “DefaultAzureCredential()”, which does the trick of our Managed Identity, without providing plain credentials here.

Step 4 – Login to Azure

If you “run” your app at this stage, you will end up getting an error like the one below. This is because, currently you do not have any connection between your laptop and azure portal. This application will work if you host this in Azure, in any resources like App Service but you cannot run this in your developer laptop/machine if you want to debug.

image

To make your app debug-able in your machine, you have to let Visual Studio login to Azure.

Go to Tools –> Options –> Azure Service Authentication

and, login to your account there.

image

Step 5 – Execute!

Now we are all set for building and running the app. Just hit F5!

image

Leave a Reply