Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 52

Azure Key Vault Secret Retrieval with .NET SDK

Recommended resources

Welcome back! In our last lesson, we explored the different types of objects Azure Key Vault can manage: secrets, keys, and certificates. We established that secrets are the fundamental building blocks for storing sensitive information like connection strings and API keys.

Today, we transition from theory and portal management to practical application development. This lesson focuses on retrieving those secrets programmatically from within a .NET application, a core skill for the AZ-204 exam and for building secure, production-ready Azure solutions. We will cover the modern .NET SDK patterns for interacting with Key Vault, setting you up to eliminate hardcoded credentials from your applications.

1. The .NET SDK for Azure Key Vault

To interact with Azure Key Vault from a .NET application, you'll primarily use two NuGet packages provided by Azure. Given your extensive background in .NET, incorporating these libraries into a project will be a familiar process.

  • Azure.Security.KeyVault.Secrets: This library provides the SecretClient, which is the main class for performing operations on secrets (create, retrieve, update, delete).
  • Azure.Identity: This library is crucial for authentication. It provides credential classes, most notably DefaultAzureCredential, which simplifies authenticating your application to Azure services.

Azure Key Vault secret client library for .NET - Microsoft Learn

This official Microsoft documentation provides the essential starting point for using the Key Vault SDK.

Focus on these parts: Install the package: Note the dotnet add package commands for both libraries. Authenticate the client: Read this section carefully. It introduces the SecretClient and, more importantly, the DefaultAzureCredential. Pay attention to the description of how DefaultAzureCredential works by trying multiple authentication methods. This is the key to writing code that works both on your local machine and when deployed to Azure. Key concepts: Briefly review the definitions of KeyVaultSecret and SecretClient to formalize your understanding.

The DefaultAzureCredential is particularly powerful. It creates a chain of credential providers and tries them in order until one succeeds. This chain includes credentials from your local development environment (like your Visual Studio or Azure CLI login) as well as credentials available in a deployed environment (like a Managed Identity). This means you can write one piece of authentication code that works everywhere.


2. Retrieving Secrets Programmatically

There are two primary patterns for retrieving secrets in an ASP.NET Core application. Let's explore both.

Approach 1: Direct Retrieval with SecretClient

The most direct way to get a secret is to instantiate a SecretClient and call its GetSecret or GetSecretAsync method. This is useful when you need to fetch a specific secret on demand within your application logic.

The following video demonstrates this pattern clearly within a modern .NET Minimal API project.

Stop Storing Secrets in appsettings.json! Use Azure Key Vault Instead

In his video "Stop Storing Secrets in appsettings.json!", Milan Jovanović shows how to use the .NET SDK for Key Vault.

Watch this first segment to see the direct retrieval pattern in action: Using SecretClient: Observe how he installs the necessary NuGet packages, creates an instance of SecretClient using the Key Vault URI and DefaultAzureCredential, and then calls GetSecret to retrieve the secret's value.

The core code pattern looks like this:

// The vault URI from your Key Vault's overview page in the Azure portal
var keyVaultUri = new Uri("https://your-key-vault-name.vault.azure.net/");

// DefaultAzureCredential handles authentication
var client = new SecretClient(keyVaultUri, new DefaultAzureCredential());

// Retrieve the secret
KeyVaultSecret secret = await client.GetSecretAsync("YourSecretName");

// Use the secret's value
string secretValue = secret.Value;

Approach 2: Integration with ASP.NET Core Configuration

While direct retrieval works, a more powerful and common pattern for ASP.NET Core applications is to integrate Key Vault directly into the configuration system (IConfiguration). This makes your Key Vault secrets available in the exact same way as settings from appsettings.json or environment variables, allowing for clean, consistent code.

This approach requires one additional package: Azure.Extensions.AspNetCore.Configuration.Secrets.

Let's return to the same video to see this elegant integration.

Stop Storing Secrets in appsettings.json! Use Azure Key Vault Instead

Milan Jovanović continues by demonstrating how to seamlessly integrate Key Vault into the ASP.NET Core configuration.

Watch these two segments: IConfiguration Integration: Pay close attention to how the AddAzureKeyVault extension method is used in Program.cs. Notice the clever way secret names with double dashes (--) in Key Vault map to hierarchical configuration keys with colons (:), like "ConnectionStrings:AzureServiceBus". Using the Options Pattern: This section demonstrates a best practice where configuration is bound to a strongly-typed C# class using IOptions<T>. As a senior developer, you'll recognize this as a clean, testable way to inject configuration into your services.

This C# code demonstrates the `IConfiguration` integration. The `Program.cs` file is modified to add Azure Key Vault as a configuration source, and a service then retrieves a secret (like a connection string) directly from the `IConfiguration` object.

This integration approach is generally recommended for application settings, connection strings, and other bootstrap configuration, as it abstracts away the specifics of Key Vault from your application's business logic.


3. Authentication in Practice: From Local to Azure

So far, DefaultAzureCredential seems magical—it just works. On your local machine, it succeeds by using the credentials from your Visual Studio or Azure CLI login.

But what happens when you deploy this code to an Azure App Service? The application is running in the cloud, and there is no "developer" logged in. This is where the application would fail, as it has no identity to present to Key Vault. The solution is to give the Azure resource itself an identity.

This next video provides a crucial end-to-end demonstration. It shows the code working locally, failing upon deployment, and then being fixed by enabling a Managed Identity.

Azure Key Vault Security Guide | Managed Identity for Web API Secrets (Hands-On Demo!)

The video "Azure Key Vault Security Guide" by Learn Smart Coding provides an excellent hands-on demonstration of the entire workflow.

Focus on these two parts: Local Execution: The presenter shows the code retrieving a secret while running locally, relying on DefaultAzureCredential picking up his logged-in user. Deployment and Managed Identity: This is the most critical part. Watch as the deployed web app initially fails with an authorization error. The presenter then enables a system-assigned managed identity for the App Service and grants that identity the Key Vault Secrets User role on the Key Vault. After this change, the app successfully retrieves the secret.

This demonstration perfectly illustrates the power of DefaultAzureCredential. The exact same application code works in both environments. Locally, it uses your identity. In Azure, it automatically uses the Managed Identity of the hosting resource (in this case, the App Service). You have successfully removed all credentials from your code and configuration files.


Conclusion

In this lesson, we bridged the gap between managing secrets in the Azure portal and using them securely in a .NET application. You now have the practical coding skills required for this essential AZ-204 topic.

Here are the key takeaways:

  • The Azure.Security.KeyVault.Secrets and Azure.Identity NuGet packages are the foundation for programmatic access.
  • You can retrieve secrets directly using SecretClient.GetSecretAsync(), which is useful for on-demand access.
  • The recommended pattern for ASP.NET Core apps is to integrate Key Vault with IConfiguration using AddAzureKeyVault, making secrets available like any other configuration setting.
  • DefaultAzureCredential is the key to authentication, enabling your code to run seamlessly on your local machine and in Azure without changes.
  • When deployed to Azure, your application resource (e.g., App Service) needs a Managed Identity with permissions to the Key Vault for DefaultAzureCredential to work.

We've just seen a practical application of a Managed Identity. In our next lesson, we will take a closer look at this concept, exploring the differences between system-assigned and user-assigned managed identities and how to configure them to provide a secure, credential-free identity for your Azure resources.