Azure Key Vault — Securely Manage Environment Specific Secrets

Merwan Chinta
CodeNx
Published in
4 min readMay 25, 2024

Managing sensitive information like API keys, database connection strings, and other secrets in a secure and organized manner is critical for any application.

Azure Key Vault provides a centralized and secure solution for managing secrets, keys, and certificates.

This article will demonstrate how to store and retrieve environment-specific secrets using Azure Key Vault in a .NET application, focusing on securely accessing an external vendor service using environment-specific API keys.

Azure Key Vault

Outline

  1. Introduction
  2. Setting Up Azure Key Vault
  3. Storing Environment-Specific Secrets in Azure Key Vault
  4. Accessing Secrets in a .NET Application
  5. Implementing Secure Access in Code
  6. Conclusion

1. Introduction

In this article, we will explore how to use Azure Key Vault to manage and secure API keys specific to different environments (development, QA, UAT, production).

We will create a .NET application that retrieves these API keys from Azure Key Vault based on the current environment and uses them to interact with an external vendor service securely.

2. Setting Up Azure Key Vault

First, we need to create an Azure Key Vault and add our environment-specific API keys as secrets.

Create Azure Key Vault

az keyvault create --name YourKeyVaultName --resource-group YourResourceGroupName --location YourLocation

3. Storing Environment-Specific Secrets in Azure Key Vault

We will store different API keys for each environment (development, QA, UAT, production) in Azure Key Vault.

Add Secrets to Azure Key Vault

az keyvault secret set --vault-name YourKeyVaultName --name "ApiKey-Dev" --value "YourDevApiKey"
az keyvault secret set --vault-name YourKeyVaultName --name "ApiKey-QA" --value "YourQaApiKey"
az keyvault secret set --vault-name YourKeyVaultName --name "ApiKey-UAT" --value "YourUatApiKey"
az keyvault secret set --vault-name YourKeyVaultName --name "ApiKey-Prod" --value "YourProdApiKey"

4. Accessing Secrets in a .NET Application

We will create a .NET application that accesses the appropriate API key from Azure Key Vault based on the current environment.

Create a .NET Core Console Application

dotnet new console -n KeyVaultExample
cd KeyVaultExample

Install Necessary NuGet Packages

dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets

5. Implementing Secure Access in Code

Configure Key Vault Access

Create a new file appsettings.json

{
"AzureKeyVault": {
"Vault": "https://YourKeyVaultName.vault.azure.net/"
},
"Environment": "Dev" // Change this value to "QA", "UAT", or "Prod" as needed
}

Update Program.cs to Integrate Azure Key Vault

using System;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace KeyVaultExample
{
class Program
{
static void Main(string[] args)
{
// Create and build the host
var host = CreateHostBuilder(args).Build();

// Retrieve the ApiKeyService instance from the DI container
var apiKeyService = host.Services.GetRequiredService<ApiKeyService>();

// Call the UseApiKey method to demonstrate using the API key
apiKeyService.UseApiKey();

// Start the application
host.Run();
}

// Configure and create the IHostBuilder
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
// Build the initial configuration from appsettings.json and other default sources
var builtConfig = config.Build();

// Retrieve the Key Vault endpoint from the built configuration
var keyVaultEndpoint = builtConfig["AzureKeyVault:Vault"];

// Check if the Key Vault endpoint is specified in the configuration
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
// Create a DefaultAzureCredential object to handle authentication to Azure Key Vault
var credential = new DefaultAzureCredential();

// Add Azure Key Vault as a configuration source to the configuration builder
// This allows the application to automatically fetch secrets from the specified Key Vault
config.AddAzureKeyVault(new Uri(keyVaultEndpoint), credential);
}
})
.ConfigureServices((context, services) =>
{
// Register ApiKeyService as a singleton service in the DI container
services.AddSingleton<ApiKeyService>();
});
}

// Service class responsible for managing and using the API key
public class ApiKeyService
{
private readonly string _apiKey;

// Constructor that retrieves the API key from the configuration
public ApiKeyService(IConfiguration configuration)
{
// Retrieve the current environment (e.g., Dev, QA, UAT, Prod) from the configuration
var environment = configuration["Environment"];

// Retrieve the API key specific to the current environment from the configuration
// This key is fetched from Azure Key Vault if configured correctly
_apiKey = configuration[$"ApiKey-{environment}"];
}

// Method to demonstrate using the API key
public void UseApiKey()
{
// For demonstration purposes, print the API key to the console
Console.WriteLine($"Using API Key: {_apiKey}");

// Here, you would use the API key to call an external service, such as:
// var client = new HttpClient();
// client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
// var response = client.GetAsync("https://external-service.com/api/resource").Result;
// Process the response...
}
}
}

Explanation

  1. Environment Configuration: In appsettings.json, we specify the current environment. This allows us to determine which API key to retrieve from Azure Key Vault.
  2. Key Vault Integration: In Program.cs, we integrate Azure Key Vault with our configuration, so secrets are fetched from the Key Vault based on the environment.
  3. Environment-Specific API Key: The ApiKeyService class retrieves the correct API key from the configuration based on the current environment and uses it to call an external service.

6. Conclusion

By centralizing the management of secrets and ensuring secure access through Azure Key Vault, we significantly reduce the risk of exposing sensitive information and enhance the security posture of our application. Azure Key Vault simplifies the process of managing secrets, keys, and certificates, providing a robust solution for securing sensitive information in cloud applications.

I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!

📚 For more insights like these, feel free to 👏 follow 👉 Merwan Chinta

--

--

Merwan Chinta
CodeNx

🚧 Roadblock Eliminator & Learning Advocate 🖥️ Software Architect 🚀 Efficiency & Performance Guide 🌐 Cloud Tech Specialist