Retrieve Azure Key Vault Key in ASP.NET Core: A Complete Guide

Azure Key Vault is a cloud-based service that helps developers securely store and manage sensitive information, including cryptographic keys, secrets, and certificates. In ASP.NET Core applications, integrating Azure Key Vault allows developers to manage cryptographic keys securely without exposing sensitive information in source code or configuration files.

In this article, we will explore how to retrieve an Azure Key Vault key in an ASP.NET Core application using C#. You will learn how to create an Azure Key Vault, configure authentication using Microsoft Entra ID, install the required NuGet packages, register the Key Vault client through dependency injection, and retrieve key metadata from an ASP.NET Core controller. We will also cover error handling and security best practices for building secure, production-ready applications.

Getting Started

Before exploring how to retrieve an Azure Key Vault key in an ASP.NET Core application, it is helpful to understand the basic process of accessing Azure Key Vault using C# and .NET.

If you are new to Azure Key Vault key retrieval, you can first read my previous article, Retrieve Azure Key Vault Key in C# and .NET Core: A Complete Guide. It explains how to configure Azure Key Vault and retrieve a cryptographic key using C# and the Azure SDK.

In this article, we will build on those concepts and focus on integrating Azure Key Vault into an ASP.NET Core application. You will learn how to configure the Key Vault client, register it using dependency injection, authenticate securely, and retrieve key information through an ASP.NET Core controller.

Prerequisites

  • An active Azure subscription.
  • An Azure Key Vault containing a cryptographic key.
  • An ASP.NET Core Web API project.
  • The required permissions to read key metadata from Azure Key Vault.
  • The .NET SDK compatible with your ASP.NET Core project.

Install the required NuGet packages

</> Bash
dotnet add package Azure.Security.KeyVault.Keys
dotnet add package Azure.Identity

  • Azure.Security.KeyVault.Keys provides the KeyClient class to manage and retrieve keys.
  • Azure.Identity provides DefaultAzureCredential for authentication with Microsoft Entra ID.

Configure Azure Key Vault

Add the following configuration to appsettings.json:
</> JSON
{
  "AzureKeyVault": {
    "VaultUri": "https://your-vault-name.vault.azure.net/",
    "KeyName": "MyEncryptionKey"
  }
}

Replace the placeholder values with your actual Key Vault URI and key name. The vault URI and key name are configuration values, not credentials. Never store client secrets or other sensitive authentication credentials in source-controlled configuration files.

Register the Key Vault client in Program.cs

</> C#
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var vaultUri = builder.Configuration[
  "AzureKeyVault:VaultUri"]
  ?? throw new InvalidOperationException(
  "Azure Key Vault URI is not configured.");
  builder.Services.AddSingleton<KeyClient>(_ =>
  new KeyClient(
  new Uri(vaultUri),
  new DefaultAzureCredential()));
  var app = builder.Build();
  app.MapControllers();
  app.Run();

Here, KeyClient is registered with ASP.NET Core's dependency injection container. DefaultAzureCredential selects an available supported authentication method, such as developer credentials locally or managed identity in Azure.

Retrieve the key using an ASP.NET Core controller

Create a controller named KeyVaultController.cs:
</> C#
using Azure;
using Azure.Security.KeyVault.Keys;
using Microsoft.AspNetCore.Mvc;
namespace AzureKeyVaultApi.Controllers
{
  [ApiController]
  [Route("api/[controller]")]
  public class KeyVaultController : ControllerBase
  {
    private readonly KeyClient _keyClient;
    private readonly IConfiguration _configuration;
    public KeyVaultController(
    KeyClient keyClient,
    IConfiguration configuration)
    {
      _keyClient = keyClient;
      _configuration = configuration;
    }
    [HttpGet("retrieve-key")]
    public async Task<IActionResult> RetrieveKey()
    {
      var keyName = _configuration[
        "AzureKeyVault:KeyName"];
        if (string.IsNullOrWhiteSpace(keyName))
        {
          return Problem(
          "Azure Key Vault key name is not configured.",
          statusCode: 500);
        }
        try
        {
          KeyVaultKey key =
          (await _keyClient.GetKeyAsync(keyName)).Value;
          return Ok(new
          {
            key.Name,
            KeyType = key.KeyType.ToString(),
            Version = key.Properties.Version,
            Enabled = key.Properties.Enabled
            });
          }
          catch (RequestFailedException ex)
          when (ex.Status == 404)
          {
            return NotFound(new
            {
              message = "The specified key was not found."
              });
            }
          }
        }
      }

How does the code work?

The controller receives KeyClient and IConfiguration through dependency injection. It reads the configured key name and calls GetKeyAsync() to retrieve the key from Azure Key Vault. If the operation succeeds, the API returns selected key metadata, including its name, type, version, and enabled status. If the key does not exist, the controller returns an HTTP 404 response.

This example retrieves key metadata and the key's public representation, not its private key material. For cryptographic operations such as signing or encryption, applications can use CryptographyClient where appropriate.

Summary

Integrating Azure Key Vault with ASP.NET Core provides a secure and maintainable way to access cryptographic keys from web applications. By using the Azure SDK, dependency injection, and secure authentication, developers can retrieve key information without embedding sensitive cryptographic material in application code.

In this guide, we explored how to configure Azure Key Vault, register the KeyClient service, retrieve key metadata through an ASP.NET Core controller, and handle common errors. These concepts provide a foundation for building ASP.NET Core applications that use Azure Key Vault for secure key management and cryptographic operations.

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال