Skip to content

Azure Key Vault in .NET: Read, Store and Load Secrets

Learn how to use Azure Key Vault in .NET: authenticate with DefaultAzureCredential, read and create secrets with SecretClient, and load them straight into IConfiguration.

Ivan GechevIvan GechevSoftware Developer
Published on
Updated
Reading time
11 min read
On this page

Every application has secrets, and our cat adoption API is no exception. It needs a connection string for its database and an API key for the service that sends adoption confirmation emails. For a long time, the easiest place to put them was the good old appsettings.json file.

The problem is that appsettings.json ends up in source control, gets copied between machines, and can be read by anyone who can see the code. Environment variables are a step up, but they still live on every server, they leak easily through logs and crash dumps, and rotating them means touching every environment by hand.

In this article, we'll move our secrets to Azure Key Vault. We'll see how keys, secrets, and certificates differ, authenticate with DefaultAzureCredential, read and create secrets with SecretClient, and finally load everything straight into IConfiguration, so the rest of our application doesn't even know Key Vault exists.

Let's dive in!

What Is Azure Key Vault

Azure Key Vault is a cloud service for storing and managing sensitive information. Instead of scattering secrets across configuration files and servers, we keep them in one place, control exactly who can read them, and get an audit trail of every access.

Key Vault stores three types of objects, and it's worth knowing the difference between them:

ObjectWhat it isTypical use
SecretsAny sensitive string valueConnection strings, API keys, passwords
KeysCryptographic keys that never leave the vaultEncryption, signing
CertificatesX.509 certificates with full lifecycle managementTLS and client certificates

In this article, we'll focus on secrets, as they are what most applications need. One interesting detail: when we store a certificate in Key Vault, its private key also becomes available as a secret with the same name. That's how applications download the full certificate when they need it.

Key Vault vs appsettings.json and Environment Variables

Before we write any code, let's see what we actually gain by moving our secrets:

  • Access control: we decide which identities can read secrets and which can change them
  • Auditing: every access is logged, so we know who read what and when
  • Rotation: we update a secret once and every application picks up the new value
  • Nothing to leak: with managed identities, there's no secret on disk or in code at all

This doesn't mean appsettings.json is going anywhere. It's still the perfect place for non-sensitive configuration like feature flags, timeouts, and the Key Vault URI itself. The rule of thumb is simple: if leaking a value would be a problem, it belongs in Key Vault.

Installing the NuGet Packages

We need four NuGet packages. We can use the .NET CLI:

CLI
C#
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets
dotnet add package Microsoft.Extensions.Azure
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets

Or the Package Manager inside Visual Studio:

PackageManager
C#
Install-Package Azure.Identity
Install-Package Azure.Security.KeyVault.Secrets
Install-Package Microsoft.Extensions.Azure
Install-Package Azure.Extensions.AspNetCore.Configuration.Secrets

Azure.Identity handles authentication, Azure.Security.KeyVault.Secrets gives us the SecretClient class, Microsoft.Extensions.Azure lets us register Azure clients in the DI container, and Azure.Extensions.AspNetCore.Configuration.Secrets plugs Key Vault into the configuration system.

Authenticating With DefaultAzureCredential

To talk to Key Vault, our application needs an identity and permissions for that identity. In the original version of this article, I used EnvironmentCredential. Today, the recommended starting point is DefaultAzureCredential.

DefaultAzureCredential tries several authentication methods in order, like environment variables, workload identity, managed identity, and developer tools such as Visual Studio and the Azure CLI, and uses the first one that works. This means the same code works on our machine and in Azure. Locally, we sign in to Visual Studio or run az login. In Azure, our app uses its managed identity. If you want to learn more about the individual credential types, you can check my article on Microsoft Graph authentication methods, as they work the same way.

The identity also needs permissions. With Azure RBAC, which is the recommended permission model for Key Vault, there are two roles we care about:

  • Key Vault Secrets User: can read secret values
  • Key Vault Secrets Officer: can also create, update, and delete secrets

Our API only reads secrets, so we assign it the first one:

Bash
az role assignment create \
  --role "Key Vault Secrets User" \
  --assignee <principal-id> \
  --scope <key-vault-resource-id>

The <principal-id> is the object ID of our app's managed identity, or our own user account for local development.

Registering SecretClient With Dependency Injection

The entry point for working with secrets is the SecretClient class. It's thread-safe and meant to be reused, so we register it once:

Program.cs
C#
using Azure.Identity;
using Microsoft.Extensions.Azure;

var builder = WebApplication.CreateBuilder(args);

var keyVaultUri = new Uri(builder.Configuration["KeyVault:Uri"]!);

builder.Services.AddAzureClients(clientBuilder =>
{
    clientBuilder.AddSecretClient(keyVaultUri);
    clientBuilder.UseCredential(new DefaultAzureCredential());
});

We read the vault URI from configuration. It isn't a secret, so it can safely live in appsettings.json:

appsettings.json
JSON
{
  "KeyVault": {
    "Uri": "https://cat-adoption-kv.vault.azure.net/"
  }
}

Then, we call the AddAzureClients() method, register a SecretClient for our vault with AddSecretClient(), and tell all Azure clients to use DefaultAzureCredential with the UseCredential() method. Now, we can inject SecretClient anywhere in our application.

Retrieving Secrets From Azure Key Vault

Let's create a small service that wraps the SecretClient:

CatSecretsService.cs
C#
using Azure;
using Azure.Security.KeyVault.Secrets;

public interface ICatSecretsService
{
    Task<string?> GetSecretAsync(string secretName, CancellationToken cancellationToken);
}

public class CatSecretsService(SecretClient secretClient) : ICatSecretsService
{
    public async Task<string?> GetSecretAsync(
        string secretName,
        CancellationToken cancellationToken)
    {
        try
        {
            KeyVaultSecret secret = await secretClient.GetSecretAsync(
                secretName,
                cancellationToken: cancellationToken);

            return secret.Value;
        }
        catch (RequestFailedException ex) when (ex.Status == 404)
        {
            return null;
        }
    }
}

There's quite a bit going on here, so let's break it down.

We use a primary constructor to inject the SecretClient. If primary constructors are new to you, I explain them in my C# Primary Constructors article.

In the GetSecretAsync() method, we call the SecretClient's GetSecretAsync() method with the secret name and pass the CancellationToken along. It returns a Response<KeyVaultSecret>, which converts implicitly to KeyVaultSecret, so we can assign it directly. The actual secret is in the Value property.

The interesting part is the error handling. When a secret doesn't exist, GetSecretAsync() doesn't return an empty result, it throws a RequestFailedException with a 404 status code. In the original version of this article, I checked the HasValue property instead. That check never fails, because a missing secret never gets that far. Here, we catch only the 404 and return null, so the caller can decide what to do. Any other error, like a 403 caused by missing permissions, still bubbles up, as it should.

Finally, we register our service:

Program.cs
C#
builder.Services.AddSingleton<ICatSecretsService, CatSecretsService>();

SecretClient is a singleton, so our service can be one as well.

Creating and Updating Secrets

Reading is what our API does most of the time, but sometimes we need to store secrets from code, for example when an admin tool generates a new API key:

CatSecretsService.cs
C#
public async Task SetSecretAsync(
    string secretName,
    string value,
    CancellationToken cancellationToken)
{
    var secret = new KeyVaultSecret(secretName, value);
    secret.Properties.ExpiresOn = DateTimeOffset.UtcNow.AddMonths(6);

    await secretClient.SetSecretAsync(secret, cancellationToken);
}

We create a new KeyVaultSecret with a name and a value and set an expiration date through the Properties.ExpiresOn property. Then, we save it with the SetSecretAsync() method.

Calling SetSecretAsync() with an existing name doesn't overwrite the secret, it creates a new version of it. The GetSecretAsync() method always returns the latest version unless we explicitly ask for an older one. This makes rotation safe, as we can always roll back. Expiration dates also make it easy to spot secrets that need rotating, and Azure can even notify us through Event Grid before they expire.

There are two things to keep in mind here. Secret names can only contain letters, numbers, and dashes. And to write secrets, our identity needs the Key Vault Secrets Officer role, not just the Key Vault Secrets User one.

Loading Key Vault Secrets Into IConfiguration

Injecting SecretClient works, but most of the time we don't want our services to know where their configuration comes from. The configuration provider solves this by loading our secrets into IConfiguration at startup:

Program.cs
C#
using Azure.Identity;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddAzureKeyVault(
    new Uri(builder.Configuration["KeyVault:Uri"]!),
    new DefaultAzureCredential());

That's all it takes. Every secret in the vault is now a regular configuration value.

Since secret names can't contain colons, the provider uses a naming convention: a double dash in the secret name becomes a colon in the configuration key. So, if we store our database connection string in a secret called ConnectionStrings--CatsDb, we can read it the same way as before:

Program.cs
C#
var connectionString = builder.Configuration.GetConnectionString("CatsDb");

The same goes for the options pattern. Let's say we store the API key for our email service in a secret called Email--ApiKey:

EmailOptions.cs
C#
public class EmailOptions
{
    public const string SectionName = "Email";

    public string ApiKey { get; set; } = string.Empty;
}
Program.cs
C#
builder.Services.Configure<EmailOptions>(
    builder.Configuration.GetSection(EmailOptions.SectionName));

Our EmailOptions class gets its ApiKey from Key Vault, and the service that uses it has no idea. If you want to learn more about this pattern, and how to test classes that depend on it, check my Options Pattern and How to Mock It article.

By default, secrets are loaded once, when the application starts. If we rotate secrets regularly, we can ask the provider to reload them:

Program.cs
C#
using Azure.Extensions.AspNetCore.Configuration.Secrets;

builder.Configuration.AddAzureKeyVault(
    new Uri(builder.Configuration["KeyVault:Uri"]!),
    new DefaultAzureCredential(),
    new AzureKeyVaultConfigurationOptions
    {
        ReloadInterval = TimeSpan.FromMinutes(30)
    });

With the ReloadInterval property, the provider checks for new values every 30 minutes. To actually see the new values in our services, we need to use IOptionsMonitor<T> instead of IOptions<T>.

Things to Watch Out For

Key Vault is easy to start with, but there are a few things I'd keep in mind before using it in production.

Don't Call Key Vault on Every Request

Key Vault has service limits and will throttle us if we send too many requests. Every call is also a network round trip. Using the configuration provider or caching the values we read with SecretClient keeps our API fast and well within the limits.

Never Log Secret Values

It sounds obvious, but it's easy to log a whole options object or configuration section while debugging. Once a secret ends up in our logs, it's no longer a secret.

Use One Vault per Application and Environment

Sharing a single vault between applications or environments makes access control harder. A separate vault for each application and each environment means our development API can never accidentally read production secrets.

Soft Delete and Purge Protection

Soft delete is enabled by default, so a deleted secret can be recovered during the retention period. For production vaults, I also recommend enabling purge protection. It prevents anyone from permanently deleting secrets before the retention period ends, but keep in mind that once we enable it, we can't turn it off.

Prefer a Specific Credential in Production

DefaultAzureCredential is great for getting started, but in production it tries several credentials before it finds the right one. Microsoft recommends switching to a specific credential, like ManagedIdentityCredential, once we know how our app runs. This makes authentication faster and more predictable.

Conclusion

Azure Key Vault gives our secrets a proper home. With DefaultAzureCredential, the same code works on our machine and in Azure, SecretClient lets us read and create secrets when we need fine-grained control, and the configuration provider makes Key Vault completely invisible to the rest of our application.

Our cat adoption API no longer has a single secret in its code or configuration files, and rotating them is now a matter of updating a value in one place.

Frequently Asked Questions

What is the difference between keys and secrets in Azure Key Vault?

Secrets are values that our application reads, like connection strings and API keys. Keys are cryptographic keys that never leave the vault. Instead of reading them, we ask Key Vault to encrypt, decrypt, or sign data with them.

Is Azure Key Vault better than environment variables?

For sensitive values, yes. Key Vault gives us access control, auditing, versioning, and central rotation, and with managed identities there's nothing stored on the server at all.

How do I read a secret from Azure Key Vault in C#?

Create a SecretClient with your vault URI and a credential, and call its GetSecretAsync() method. The secret value is in the Value property of the returned KeyVaultSecret.

What happens if a secret doesn't exist?

The GetSecretAsync() method throws a RequestFailedException with a 404 status code.

How do I use Azure Key Vault locally without a managed identity?

Sign in to Visual Studio or run az login. DefaultAzureCredential will use your account, as long as it has the Key Vault Secrets User role on the vault.

> keep reading

7 min read

API Key Authentication in .NET Minimal APIs

API key authentication is a common approach to securing APIs by requiring clients to provide a unique key with each request. In this article, we will explore how to implement API key authentication in .NET Minimal APIs while supporting multiple API keys.

6 min read

Efficient Data Transfer With Azure Queue Storage

If you are ready to optimize your data transfer workflows and supercharge your cloud-based systems, let us delve into the world of Azure Storage Queues and discover how they can revolutionize the way you move data within your digital ecosystem.