Integrating Azure Key Vault with a .NET 7 Web Application

Introduction

Azure Key Vault is a secure and reliable service for storing sensitive data such as secrets, keys, and certificates. In this blog, we'll demonstrate how to create a .NET 7 web application and integrate it with Azure Key Vault for secure storage and access to secrets.

Prerequisites

Before we begin, ensure you have the following installed on your machine.

Step 1. Create a .NET 7 Web Application

Open the terminal/command prompt and create a new .NET 7 web application.

dotnet new web -n AzureKeyVaultDemo

Now, navigate to the project folder:

cd AzureKeyVaultDemo

Step 2. Install Required NuGet Packages

Install the required NuGet packages:

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

These packages will allow our application to interact with Azure Key Vault and use the appropriate authentication methods.

Step 3. Set Up Azure Key Vault

To set up Azure Key Vault, follow these steps,

  1. Log in to the Azure Portal.
  2. Click on Create a resource.
  3. Search for Key Vault and click on the result.
  4. Click Create and fill in the required information, such as subscription, resource group, key vault name, and region.
  5. Click Review + create and then Create to create the Key Vault.

Step 4. Add a Secret to Azure Key Vault

  1. In the Azure Portal, navigate to the Key Vault you just created.
  2. Under the Settings section, click on Secrets.
  3. Click +Generate/Import.
  4. Fill in the required information, such as the secret name and value, and click Create.

Step 5. Configure the .NET 7 Web Application

Open the Program.cs file in your project folder and update it as follows.

using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add Azure Key Vault configuration
builder.Configuration.AddAzureKeyVault(
    new Uri("https://<Your-Key-Vault-Name>.vault.azure.net/"),
    new DefaultAzureCredential());

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Make sure to replace <Your-Key-Vault-Name> with the actual name of your Key Vault.

Step 6. Access the Secret in the .NET 7 Web Application

To access the secret in your application, update the HomeController.cs as follows.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using AzureKeyVaultDemo.Models;

namespace AzureKeyVaultDemo.Controllers 
{
  public class HomeController: Controller 
  {
    private readonly ILogger < HomeController > _logger;
    private readonly IConfiguration _configuration;
    
    public HomeController(ILogger < HomeController > logger, IConfiguration configuration) 
    {
      _logger = logger;
      _configuration = configuration;
    }

    public IActionResult Index() {
      // Read the secret from the Azure Key Vault
      string secretValue = _configuration["YourSecretName"];

      // Pass the secret value to the view
      ViewBag.SecretValue = secretValue;

      return View();
    }

    // Other action methods and methods of HomeController
  }
}

Replace `YourSecretName` with the actual name of your secret in Azure Key Vault.

Step 7. Display the Secret Value in the View

Update the `Index.cshtml` file in the `Views/Home` folder to display the secret value.

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Secret value from Azure Key Vault: @ViewBag.SecretValue</p>
</div>

Step 8. Test the Application

Now, run the application using the following command.

dotnet run

Navigate to the URL displayed in the terminal (usually https://localhost:5001/) and verify that the secret value from Azure Key Vault is displayed on the home page.

Summary

the article provides a step-by-step guide for developers looking to perform CRUD operations using ASP.NET Core and .NET 7.


Similar Articles