Securing Sensitive Data with Azure Key Vault in .NET Applications

by admin

In modern application development, storing sensitive information like API keys, database connection strings, and certificates directly in yonur code or configuration files poses significant security risks. Azure Key Vault offers a robust solution for securely managing these sensitive pieces of information.

Why Store Sensitive Information Securely?

  • Security Risk Mitigation: Prevents exposure of credentials in source code repositories
  • Simplified Management: Centralized location for all secrets across multiple applications
  • Access Control: Fine-grained permissions management
  • Audit Capabilities: Track who accessed what and when

Setting Up Azure Key Vault

Step 1: Create an Azure Key Vault

  1. Log into the Azure Portal
  2. Navigate to “Key Vaults” and select “Create”
  1. Fill in the required information:
    • Subscription: Your Azure subscription
    • Resource Group: Create new or select existing
    • Key Vault Name: Choose a unique name
    • Region: Select your preferred region
  2. Click Review + Create followed by Create

Step 2: Configure Managed Identity for Your Application

For your application to access Key Vault securely, you need to:

1. Enable Managed Identity for your App Service:

  1. Navigate to your Azure App Service
  2. Select Identity from the left menu
  1. Under the System assigned tab, toggle the status to On
  1. Click Save to confirm

2. Grant the Managed Identity access to the Key Vault

  1. Go to your Key Vault
  2. Select Access policies from the left menu
  3. Click + Add Access Policy
  4. Select Get and List permissions under Secret permissions
  1. Under Select principal, search for your App Service name
  2. Select your App Service and click Add
  3. Don’t forget to click Save on the main Access policies page

This step ensures your application can access secrets from Key Vault without needing to store any credentials.

Integrating Azure Key Vault with .NET Applications

Install Required Packages

Add these NuGet packages to your project:

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

These allow you to authenticate with Azure and load secrets into your configuration.

Setup App Settings

Find your Key Vault URI in the resource Overview page under the Vault URI section.

Add your key vault into app settings so that the code can use it to access the confidential information stored in the vault.

{
  "KeyVault": "https://<your-keyvault-name>.vault.azure.net/"
}

Setup Program.cs

The following code loads configuration from appsettings.json, then connects to Azure Key Vault in production using DefaultAzureCredential so secrets can be accessed like normal config values.

if (builder.Environment.IsProduction())
{
    // Load base and environment-specific config files
    string environment = Environment.GetEnvironmentVariable("ENVIRONMENT");
    string jsonFile = $"appsettings.{environment}.json";

    builder.Configuration
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile(jsonFile, optional: true);

    // Get Key Vault URL from config
    string? keyVaultUrl = builder.Configuration["KeyVault"];

    // Authenticate using managed identity or local credentials
    var credentials = new DefaultAzureCredential();

    // Add secrets from Azure Key Vault to app configuration
    builder.Configuration.AddAzureKeyVault(new Uri(keyVaultUrl), credentials);
}

Lets break this code down and explain what each section does:

  1. Checks if environment is production
if (builder.Environment.IsProduction())
  1. Reads the current app environments config:
string environment = Environment.GetEnvironmentVariable("ENVIRONMENT");
string jsonFile = $"appsettings.{environment}.json";
builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile(jsonFile, optional: true);
  1. Authorises access to the key vault using your Managed Identity.

DefaultAzureCredential tries multiple authentication methods in order. Like environment variables, managed identity, and developer tools (e.g. Visual Studio), and uses the first one that works.

You can replace it with a more specific credential like “ManagedIdentityCredential” if needed, but for most cases, “DefaultAzureCredential” is the easiest and simplest choice.

var credentials = new DefaultAzureCredential();

Access the Key Vault values in your code.

  1. Setup the key value pair in your appsettings.json.
"ExternalServiceOptions": {
  "ApiKey":"",
  "BaseUrl":""
}
  1. Create a model to represent the Key Vault entity.
public class ExternalServiceOptions
{
    public string BaseUrl { get; set; }
    public string ApiKey { get; set; }
}
  1. Access the value retrieved from your Azure Key Vault by using the IOptions Interface combined with a custom class to represent the entity.
public class HereMapsApiService : IHereMapsApiService
{
   private readonly ExternalServiceOptions _serviceOptions;

   public TestService(IOptions<HereMapsRoutingApiClientOptions> serviceOptions)
       {
           _serviceOptions = serviceOptions?.Value;
       }

   public async Task SampleMethod()
   {
        var keyVaultValue = _apiOptions.ApiKey;
   }
}

Related Posts

Leave a Comment