How to Create and Use Key Vault References in .NET Core Web API

Introduction

In this article, you’ll learn how to use Azure App Configuration with Azure Key Vault in an ASP.NET Core Web API. By combining these services, you can securely manage sensitive data and configuration settings in one place. Azure App Configuration allows your application to use Key Vault references by creating keys that point to values stored in Key Vault. Rather than storing sensitive data directly, App Configuration uses URIs that reference Key Vault values, ensuring security and flexibility.

This article will guide you through setting up Key Vault references in Azure App Configuration and accessing them within your ASP.NET Core Web API application.

Prerequisites

Before proceeding, make sure to complete the following by reading my previous article. Click here to read.

  1. Create an App Configuration Store.
  2. Set up a Connection String for App Configuration in your ASP.NET Core Web API.

Table of Contents

  1. What is Azure Key Vault?
  2. What are Key Vault References?
  3. Setting Up Azure Key Vault
  4. Adding Secrets to Azure Key Vault
  5. Add a Key Vault Reference to App Configuration
  6. Update your Code to Use the Key Vault Reference
  7. Best Practice
  8. Conclusion

What is Azure Key Vault?

Azure Key Vault is a cloud service by Microsoft that provides a secure storage solution for managing sensitive information like passwords, API keys, certificates, and encryption keys. Key Vault helps prevent hardcoding secrets in your application code by centralizing secrets management and integrating with Azure's security and compliance tools.

Key Benefits of Azure Key Vault

  • Centralized Management: Securely manage access to secrets from a single location.
  • Access Control: Use Role-Based Access Control (RBAC) and Azure Active Directory (AAD) to control access to Key Vault.
  • Automatic Secret Rotation: Helps manage the lifecycle of secrets with automated key and secret rotations.

What are Key Vault References?

Key Vault References are a mechanism provided by Azure App Configuration that allows applications to reference secrets stored in Azure Key Vault. Instead of retrieving secrets directly in the code, you configure them as references in Azure App Configuration and access them through your application’s configuration settings.

This approach offers

  • Simplified Access: Access Key Vault secrets directly as configuration values without additional code.
  • Enhanced Security: Secrets remain secure and can be easily updated in Azure Key Vault without modifying the application code.

Setting Up Azure Key Vault

To create and configure an Azure Key Vault:

Step 1. Log into the Azure Portal

Step 2. Create a New Key Vault

  • Search for Key Vault in the search bar and select Create.

Azure key-vaults

  • Fill in the necessary details
    • Subscription: Select the Azure subscription.
    • Resource Group: Choose an existing resource group or create a new one.
    • Name: Provide a unique name for your Key Vault.
    • Region: Choose a location close to your application for optimal performance.

fill all the details

  • Click Review + Create and then Create to set up the Key Vault.

review and create

Adding Secrets to Azure Key Vault

Next, let’s add a secret to the vault, which we’ll later reference in App Configuration. For this example, we’ll add a simple message as a test secret.

  1. Navigate to Secrets
    • From the Key Vault properties page, select Secrets.
    • Click + Generate/Import.
      generate key secret
  2. Enter Secret Details
    • Upload options: Select Manual.
    • Name: Enter Message.
    • Value: Enter Hello from Key Vault.
    • Leave other fields at their default values.
      secret details
  3. Create the Secret: Select Create to save the secret.

Repeat this process for all sensitive data your ASP.NET Core Web API will use, like API keys or connection strings.

Add a Key Vault Reference to App Configuration

To link our Key Vault secret to App Configuration, we’ll create a reference within the App Configuration service.

  1. Open App Configuration
    • Locate the App Configuration store instance created in the previous quickstart, then select it.
    • Choose Configuration Explorer from the menu.
  2. Create Key Vault Reference
    • Select + Create > Key vault reference and provide the following details:
      • Key: Enter TestApp:Settings:KeyVaultMessage.
      • Label: Leave blank (optional).
      • Subscription, Resource Group, and Key Vault: Select the Key Vault you created earlier.
      • Secret: Choose the secret named Message and click Apply.

secret reference app config

Update Your Code to Use Key Vault References

To retrieve secrets from Azure Key Vault using App Configuration in your ASP.NET Core Web API, we’ll need to install the required packages and update the Program.cs file.

Step 1. Add Required NuGet Packages

dotnet add package Azure.Identity
dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration

Step 2. Update Program.cs file

var builder = WebApplication.CreateBuilder(args);

// Retrieve the App Configuration connection string
string connectionString = builder.Configuration.GetConnectionString("AppConfig");

// Load configuration from Azure App Configuration and connect to Key Vault
builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect(connectionString);

    // Configure Key Vault access
    options.ConfigureKeyVault(keyVaultOptions =>
    {
        keyVaultOptions.SetCredential(new DefaultAzureCredential());
    });
});

var app = builder.Build();
app.Run();

In the above code

  • Connection String: The 'AppConfig' connection string is retrieved from your configuration settings, allowing the app to connect to Azure App Configuration.
  • AddAzureAppConfiguration: This method loads configuration settings from App Configuration, including our Key Vault reference.
  • ConfigureKeyVault: Uses DefaultAzureCredentials to authenticate with Key Vault. DefaultAzureCredentials automatically detects the appropriate authentication method based on the environment, whether local or deployed.

Step 3. Access the Key Vault Reference in Code

With this setup, any Key Vault references configured in App Configuration are accessible as standard configuration values.

public class MyService
{
    private readonly IConfiguration _configuration;

    public MyService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string GetMessage()
    {
        // Retrieve the message from Key Vault through App Configuration
        return _configuration["TestApp:Settings:KeyVaultMessage"];
    }
}

This method fetches the latest version of the secret directly from Key Vault without needing to embed sensitive data in your code.

Best Practices

  1. Use Managed Identity for Authentication: Managed Identity simplifies authentication and eliminates the need for hardcoded credentials in your application code.
  2. Implement Access Control: Use Azure Role-Based Access Control (RBAC) to restrict access to Key Vault.
  3. Enable Secret Rotation: Regularly rotate secrets to minimize exposure risk.
  4. Monitor Access Logs: Use Azure Key Vault’s logging features to monitor access and detect unusual activity.
  5. Keep App Configuration and Key Vault Separate: While App Configuration and Key Vault work together, each service has a specific purpose—use App Configuration for application settings and Key Vault for sensitive secrets.

Conclusion

Integrating Azure App Configuration with Azure Key Vault in an ASP.NET Core Web API enhances your application’s security and flexibility by separating sensitive data management from other configurations. With Key Vault references, your application retrieves secrets securely, without hardcoding them in your codebase, and allows centralized control over all configurations.

References

Microsoft Azure Official Documentation

Thank You, and Stay Tuned for More!

More Articles from my Account