C# — Azure Key Vault and Service Principal

Michal Molka
2 min readDec 22, 2023

Today I want to show you how to use Azure Key Vault from C# code using a service principal. The topic is pretty simple. So, let’s make our hands dirty without further ado.

In the first step we configure a service principal. App registrations -> New registration.

The second step is to assign a proper access to Key Vault for the service principal. If you are used to other Azure services you can think you should seek to an Access Control (IAM) section. Indeed you can. But you have more control in an Access policies section. By hitting a Create button, you have more detailed access settings.

In this case, we only want fetch secrets. So, we can restrict Secret permissions to Get and List. The next step is to select previously created service principal.

We can switch over to our app. Firstly we use two libraries:

  • Azure.Security.KeyVault.Secrets,
  • Azure.Identity.

To create a credential we need to possess:

  • a tenant id,
  • a service principal client id,
  • a service principal client secret.

In this code, I’ve taken out pure string values to an AzureVariables separate static class for convenience.

So, we have libraries installed, and authentication data on a plate. In order to create a credential we use mentioned authentication data. Thus the created credential along with Key Vault URI is used to create a Secret Client.

The last thing is obvious, we use the Secret Client to get a secret from Key Vault. In this case the secret name is “cosmosdb-primary”.

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

namespace key_vault;
class Program
{
static async Task Main(string[] args)
{
var credential = new ClientSecretCredential(AzureVariables.tenantId, AzureVariables.clientId, AzureVariables.clientSecret);
var client = new SecretClient(new Uri(AzureVariables.keyVaultUri), credential);
var secret = await client.GetSecretAsync("cosmosdb-primary");
Console.WriteLine($"Your secret is '{secret.Value.Value}'.");
}
}

You can check the code out at GitHub.

--

--