Integrate Azure Key Vault with ASP.NET Core

published on 16 September 2024

Azure Key Vault secures sensitive data for ASP.NET Core apps. Here's what you need to know:

  • Stores secrets, keys, and certificates in one secure place
  • Integrates with ASP.NET Core's configuration system
  • Allows easy secret updates without code changes
  • Provides access control and usage tracking

To integrate Azure Key Vault with ASP.NET Core:

  1. Set up an Azure account and Key Vault
  2. Install required NuGet packages
  3. Configure your project to use Key Vault
  4. Update code to fetch secrets

Key benefits:

  • Improved security
  • Centralized secret management
  • Easy secret rotation

Common challenges:

  • Access issues
  • Network connectivity problems
  • Identity configuration

Quick Comparison:

Feature Local Secrets Azure Key Vault
Security Less secure More secure
Management Manual Centralized
Scalability Limited Highly scalable
Cost Free Pay-per-use
Access Control Basic Advanced

Azure Key Vault enhances your app's security, but remember to follow best practices in your overall app design and deployment.

Before You Start

Let's get you set up for integrating Azure Key Vault with your ASP.NET Core app.

Azure Account Setup

You need an active Azure account. No account? Sign up at https://azure.microsoft.com/.

Required Software

Here's what you'll need:

Item Version Notes
.NET Core SDK 7.0+ Get it from Microsoft's site
Visual Studio 2022 Free Community edition works
Azure CLI Latest Optional but useful

Basic Skills

It helps to know:

  • ASP.NET Core basics
  • Azure resource management
  • C# fundamentals

Don't sweat it if you're not an expert. You'll learn as you go.

Setting Up Your Environment

1. Create an ASP.NET Core project

Fire up Visual Studio 2022. Make a new "Console App (.NET Core)" project with ".NET 7.0" framework.

2. Register your app with Azure AD

Head to the Azure portal:

  • Go to "Azure Active Directory" > "App registrations"
  • Hit "New registration" and follow the steps

3. Set up Azure Key Vault

In the Azure portal:

  • Search for "Key vaults"
  • Click "Add" to create one
  • Fill in the details
  • Add a secret named "VerySecretValue" for testing

"Azure Key Vault is your secret weapon for keeping sensitive info under wraps in ASP.NET Core apps. It's a cloud service that stores and manages all those hush-hush details your app needs to function."

Now you're ready to roll!

Creating an Azure Key Vault

Azure Key Vault

Let's set up an Azure Key Vault to secure your ASP.NET Core app:

Make a New Key Vault

  1. Log into Azure portal
  2. Hit "Create a resource", search "Key Vault"
  3. Pick "Key Vault", click "Create"
  4. Fill in the details:
    • Subscription
    • Resource group
    • Key vault name (3-24 characters, alphanumeric and hyphens)
    • Region
    • Pricing tier (Standard or Premium)

"Azure Key Vault is your secret weapon for keeping sensitive info under wraps in ASP.NET Core apps." - Microsoft Azure Documentation

Set Access Rules

After creation:

  1. Go to your Key Vault
  2. Click "Access policies" under Settings
  3. Hit "Add Access Policy"
  4. Choose permissions
  5. Select who gets access

For more control, use RBAC:

  1. In Key Vault, go to "Access control (IAM)"
  2. Click "Add" > "Add role assignment"
  3. Pick a role
  4. Choose who gets it

Store Secrets

Add a secret:

  1. Click "Secrets" in left menu
  2. Hit "Generate/Import"
  3. Name it
  4. Enter the value
  5. Set optional properties
  6. Click "Create"

Or use Azure CLI:

az keyvault secret set --vault-name "YourKeyVaultName" --name "SecretName" --value "SecretValue"

Setting Up Your ASP.NET Core Project

ASP.NET Core

Let's get your project ready for Azure Key Vault. Here's what you need to do:

Create a New Project

  1. Open Visual Studio 2019
  2. Create a new ASP.NET Core Web API project
  3. Choose C#, .NET 5.0
  4. Skip authentication, HTTPS, Docker, and OpenAPI

Add Packages

Install these NuGet packages:

Install-Package Azure.Extensions.AspNetCore.Configuration.Secrets
Install-Package Azure.Identity

Configure Project File

Add this to your .csproj file:

<PropertyGroup>
  <UserSecretsId>12345678-1234-1234-1234-123456789012</UserSecretsId>
</PropertyGroup>

Set Local Secrets

Use these commands:

dotnet user-secrets set "SecretName" "secret_value_1_dev"
dotnet user-secrets set "Section:SecretName" "secret_value_2_dev"

"Use '_prod' instead of '_dev' for production secrets in Azure Key Vault", - Microsoft Azure docs.

Update appsettings.json

Add this KeyVault section:

{
  "KeyVault": {
    "VaultUri": "https://your-vault-name.vault.azure.net/"
  }
}

That's it. Your project is now ready for Azure Key Vault.

Connecting ASP.NET Core to Azure Key Vault

Let's hook up your project to Azure Key Vault. We'll tweak some config files and startup code.

Update appsettings.json

Add this to your appsettings.json:

{
  "KeyVault": {
    "VaultUri": "https://your-vault-name.vault.azure.net/"
  }
}

Swap your-vault-name with your actual Key Vault name.

Modify Program.cs

Open Program.cs and add these using statements:

using Azure.Identity;
using Microsoft.Extensions.Configuration;

Then, update CreateHostBuilder:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            var builtConfig = config.Build();
            var keyVaultEndpoint = builtConfig["KeyVault:VaultUri"];

            if (!string.IsNullOrEmpty(keyVaultEndpoint))
            {
                config.AddAzureKeyVault(
                    new Uri(keyVaultEndpoint),
                    new DefaultAzureCredential());
            }
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

This code grabs the Key Vault URI and, if it exists, adds Azure Key Vault as a config source. It uses DefaultAzureCredential for auth, which is pretty flexible.

"DefaultAzureCredential is like a Swiss Army knife for Azure auth. It tries different methods until one works, making it super handy for various deployment scenarios." - Azure SDK docs

That's it! Your ASP.NET Core app is now ready to pull secrets from Azure Key Vault.

Ways to Log In to Key Vault

Azure Key Vault gives you three main ways to log in:

Managed Identity

This is the easiest and safest way. It's like having an automatic pass for your Azure resources. Here's how to set it up:

1. Turn on Managed Identity for your Azure resource

2. Give that identity access to your Key Vault

For an App Service, it's as simple as:

  1. Find "Identity" in your App Service
  2. Click "System assigned"
  3. Switch it "On"
  4. Hit "Save"

Then, just add an access policy in your Key Vault for this identity.

Client Secret

This method uses a service principal with a secret. It's not as secure as Managed Identity, but it works when you can't use Managed Identity.

To use it:

  1. Register your app in Azure Active Directory
  2. Make a client secret
  3. Let the app access your Key Vault
  4. Use the client ID and secret in your code

Remember: Keep that client secret safe and change it often!

Certificate

This option sits between the other two. It's safer than client secrets but needs more setup.

To use a certificate:

  1. Create one
  2. Upload it to your Azure AD app
  3. Set up your app to use it

Here's a quick comparison:

Method Good Not So Good
Managed Identity Auto-manages credentials, No secrets in code Only for Azure resources
Client Secret Works anywhere, Easy setup You have to manage secrets
Certificate Safer than client secrets, Can use outside Azure Tricky setup, Need to manage certificates

Pick the one that fits your needs best.

Getting Secrets in Your App

You've set up Azure Key Vault and connected it to your ASP.NET Core app. Now what? Let's get those secrets!

Using IConfiguration

The easy way? Use IConfiguration:

public class HomeController : Controller
{
    private readonly IConfiguration _config;

    public HomeController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Index()
    {
        var dbConnection = _config["DatabaseConnection"];
        var apiKey = _config["Section:ApiKey"];
        // Use these secrets in your code
    }
}

Simple, right? But it's not perfect. You can't control when secrets are fetched.

Using Dependency Injection

Want more control? Try dependency injection:

1. Set up a service in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ISecretManager, SecretManager>();
}

2. Create a SecretManager class:

public class SecretManager : ISecretManager
{
    private readonly SecretClient _client;

    public SecretManager(IConfiguration config)
    {
        var kvUrl = config["AzureKeyVault:Url"];
        _client = new SecretClient(new Uri(kvUrl), new DefaultAzureCredential());
    }

    public async Task<string> GetSecretAsync(string secretName)
    {
        var secret = await _client.GetSecretAsync(secretName);
        return secret.Value.Value;
    }
}

3. Use it in your controllers:

public class HomeController : Controller
{
    private readonly ISecretManager _secretManager;

    public HomeController(ISecretManager secretManager)
    {
        _secretManager = secretManager;
    }

    public async Task<IActionResult> Index()
    {
        var dbConnection = await _secretManager.GetSecretAsync("DatabaseConnection");
        // Use the secret
    }
}

This way, you're in charge. Fetch secrets when you need them and handle errors like a pro.

Method Pros Cons
IConfiguration Easy, works out of the box Less control
Dependency Injection More control, on-demand fetching More setup

One last thing: ALWAYS handle exceptions when fetching secrets. Key Vault can fail due to network issues or access problems. Don't let it crash your app!

sbb-itb-29cd4f6

Handling Errors and Logging

Let's talk about managing errors and logging when using Azure Key Vault in your ASP.NET Core app. It's not just good practice - it's essential for keeping things secure and fixing problems.

Error Handling

Wrap your Key Vault operations in try-catch blocks. Here's a quick example:

try
{
    var secret = await _secretClient.GetSecretAsync("MySecret");
    // Use the secret
}
catch (RequestFailedException ex)
{
    if (ex.Status == 429)
    {
        // Too many requests - back off and retry
    }
    else if (ex.Status == 403)
    {
        // Oops, we're not allowed to do that
    }
    _logger.LogError($"Secret retrieval failed: {ex.Message}");
}

For those pesky 429 errors (too many requests), use a backoff strategy:

1. Wait a second, try again 2. Still no luck? Wait 2 seconds, retry 3. Keep doubling the wait time up to about 16 seconds

This helps you play nice with Key Vault when things get busy.

Logging

Want to keep tabs on what's happening with your Key Vault? Set up logging:

1. Find your Key Vault in the Azure portal 2. Go to "Diagnostic settings" 3. Add a new setting 4. Pick "audit" and "allLogs" 5. Choose where to send the logs

Here's how to do it with Azure CLI:

az monitor diagnostic-settings create --name myKeyVaultLogs \
    --resource <your-key-vault-resource-id> \
    --logs '[{"category": "AuditEvent","enabled": true}]' \
    --storage-account <your-storage-account-id>

This logs all the API requests, including the ones that didn't work out.

Monitoring and Alerts

Keep an eye on your Key Vault with Azure Monitor. Here are some things to watch:

Metric What it means When to worry
Availability Is Key Vault up and running? If it's not 100%
Latency How fast are operations? Over 1000 ms
Total Requests How many API calls? Sudden big changes

To set up an alert:

1. Find your Key Vault in Azure portal 2. Go to "Alerts" under Monitoring 3. Hit "New alert rule" 4. Pick your metric and set the trigger 5. Fill in the alert details

Security Tips

When using Azure Key Vault with ASP.NET Core, security is key. Here's how to keep your secrets safe:

Changing Secrets Regularly

Change your secrets often. Microsoft says every two years, but for critical systems, do it more.

Azure Key Vault now does this for you:

1. Set up a rotation policy 2. Turn on auto-rotation 3. Use Azure CLI or PowerShell to manage

Heads up: Azure charges $1 per scheduled rotation. Manual rotations? Free.

Limiting Access Rights

Give people only the access they need:

  • Use different key vaults for each app and environment
  • Use Azure RBAC for apps needing constant access
  • For admins, use just-in-time RBAC roles
  • Lock down network access

Here's a quick look at access control:

Method Good Bad
RBAC Detailed control, works with Azure AD Takes more time to set up
Access Policies Easy to set up Has security weak spots

Tracking Key Vault Usage

Keep an eye on your Key Vault:

  • Turn on logging
  • Use Azure Monitor
  • Set up alerts

Watch these:

Metric Normal Check If
Availability 99.9% - 100% Below 99.9%
API Latency < 250ms Over 500ms often
Total Requests Depends on your app Big jumps or drops

Testing Your Setup

Let's dive into testing your ASP.NET Core and Azure Key Vault integration. We'll cover two main approaches: local tests and full Azure Key Vault tests.

Local Tests with User Secrets

For local development, the Secret Manager tool is your friend. Here's how to use it:

1. Open a command prompt in your project's root folder.

2. Set up secrets with these commands:

dotnet user-secrets set "SecretName" "secret_value_1_dev"
dotnet user-secrets set "Section:SecretName" "secret_value_2_dev"

Now, let's use these secrets in your app:

public class IndexModel : PageModel
{
    private readonly IConfiguration _configuration;

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

    public void OnGet()
    {
        ViewData["Secret"] = _configuration["SecretName"];
    }
}

Full Tests with Azure Key Vault

Want to test in a production-like environment? Here's what you need to do:

  1. Create an Azure Key Vault
  2. Store your secrets in the vault
  3. Set up your app to connect to Key Vault

To test the connection:

public class TestController : Controller
{
    private readonly IConfiguration _configuration;

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

    public IActionResult Index()
    {
        var secret = _configuration["AzureKeyVault:SecretName"];
        return Content($"Secret value: {secret}");
    }
}

Run this code and check if it grabs the right secret from Key Vault.

Test Type Pros Cons
Local with User Secrets Quick, easy setup Not exactly like production
Full with Azure Key Vault Mirrors production Takes more time, needs Azure setup

Don't ever commit secrets to source control, even when testing.

"These small changes in Registry forced TLS1.2, and now Azure authorized my local development environment." - Konrad, Author

If you hit TLS errors while testing locally, you might need to tweak your Windows Registry to enable TLS 1.2.

Deployment Tips

Deploying your ASP.NET Core app with Azure Key Vault? Here's how to do it right:

Separate Key Vaults

Use different vaults for dev, preprod, and production:

Environment Key Vault Name
Development dev-myapp-keyvault
Preproduction preprod-myapp-keyvault
Production prod-myapp-keyvault

Lock It Down

Use Azure RBAC:

  • Assign roles at Key Vault scope
  • Use multi-factor auth for privileged access
  • Require approvals for just-in-time RBAC roles

Don't Delete by Mistake

Turn on purge protection. It's like a safety net for your secrets.

Keep an Eye Out

Use Azure Monitor. It's like a security camera for your vaults.

Fresh Secrets

Change 'em regularly:

Secret Type How Often
API Keys 30 days
Database Passwords 60 days
SSL Certificates 90 days

Use Managed Identities

Let Azure handle the auth. No more secrets in your code!

Cache It

Store secrets in your app for 8+ hours. Fewer calls to Key Vault = faster app.

Control Who Gets In

Limit IP access:

az keyvault network-rule add --name <your-key-vault-name> --ip-address <your-ip-address>/32

Config Per Environment

Use different appsettings.json files:

  • appsettings.Development.json
  • appsettings.Production.json

Now your app's ready for the big leagues!

Common Problems and Fixes

Integrating Azure Key Vault with ASP.NET Core? Here are some issues you might face and how to fix them:

Access Denied

Got a "KeyVaultErrorException: Access denied" on Azure? Try this:

  1. Check Key Vault access policy
  2. Verify app permissions
  3. Restart web app after changes

Can't Connect to Key Vault

"The connection to data plane failed"? Do this:

  1. Review firewall rules
  2. Ensure app can reach Key Vault
  3. Using Private Link? Double-check setup

Certificate Issues

Problem Fix
Can't fetch certificate Check HTTPS listeners
Certificate disabled Re-enable in Key Vault
Certificate deleted Recover from "Managed deleted certificates"

Identity Problems

App can't use its identity?

  1. Verify identity exists
  2. Create new if needed
  3. Set correct permissions

Network Troubles

Key Vault has network restrictions?

  1. Add app's virtual network to allowed list
  2. Check NSG rules

Subscription Issues

Key Vault subscription off?

  1. Go to Azure portal
  2. Find subscription
  3. Turn it on

Debugging Tips

Hidden errors? Try:

  1. Run dotnet run (yourApplicationName).dll
  2. Check output for errors
  3. Look in Windows Event Viewer under "Application" logs

Use separate Key Vaults for dev, test, and production. It's cleaner and safer.

"The error message states that there is a problem with network connection between Azure key vault and client it could be following reasons." - Akhilesh, Microsoft Vendor

Monitor your Key Vault with Azure Monitor. It's like a security camera for your secrets.

Making Your App Faster

Want to speed up your app when using Azure Key Vault with ASP.NET Core? Here's how:

Storing Secrets Temporarily

Cache secrets in memory to slash Azure Key Vault calls:

public class AzureKeyVaultCertificateProvider
{
    private readonly IMemoryCache _cache;
    private readonly SecretClient _secretClient;

    public AzureKeyVaultCertificateProvider(IMemoryCache cache, SecretClient secretClient)
    {
        _cache = cache;
        _secretClient = secretClient;
    }

    public async Task<X509Certificate2> GetCertificateAsync(string certificateName)
    {
        if (!_cache.TryGetValue(certificateName, out X509Certificate2 certificate))
        {
            var secret = await _secretClient.GetSecretAsync(certificateName);
            certificate = new X509Certificate2(Convert.FromBase64String(secret.Value.Value));
            _cache.Set(certificateName, certificate, TimeSpan.FromHours(5));
        }
        return certificate;
    }
}

This approach cuts down on repeated Key Vault calls, saving time and resources.

Reducing Key Vault Calls

Cut down on API calls to Azure Key Vault:

Strategy Description Benefit
Batching Group multiple secret requests Less network overhead
Load at startup Fetch secrets at app init Lower per-request latency
Fan-out pattern One node fetches and shares Fewer total Key Vault calls

"The cost of Azure Key Vault is $0.03 USD per 10,000 retrievals." - Microsoft Azure Pricing

By implementing these strategies, you'll speed up your app AND keep costs in check.

More optimization tips:

  • Cut unused auth options
  • Use ReloadInterval to refresh secrets without restarts
  • Try the Azure.Extensions.AspNetCore.Configuration.Secrets package

Wrap-up

Integrating Azure Key Vault with ASP.NET Core boosts your app's security. Here's why it's worth it:

  1. One secure spot for secrets: Keep all sensitive data in one place. It's easier to manage across your app.

  2. Better protection: Key Vault encrypts your secrets. This guards against breaches and unauthorized access.

  3. Easy secret updates: Change a secret in Key Vault, and your app uses it right away. No redeploy needed.

  4. Handles high demand: Key Vault can take lots of requests and stay up even when things go wrong.

  5. Tracks usage: Built-in features let you see who's accessing your secrets and when.

To make the most of Key Vault with ASP.NET Core:

  • Use different vaults for dev, staging, and production
  • Control who can access your secrets
  • Turn on purge protection to prevent accidental deletions
  • Set up alerts for unusual access

Key Vault improves security, but it's not perfect. Always use good security practices in your app design and deployment.

FAQs

How do I use Azure Key Vault in .NET Core?

Here's how to use Azure Key Vault in .NET Core:

1. Set up Key Vault

Create a Key Vault in Azure Portal. Go to "Create a resource", search for "Key Vault", and set it up with your desired name and resource group.

2. Add secrets

In your Key Vault, go to "Secrets" under "Settings". Click "Generate/Import" to add new secrets.

3. Configure your app

Install the Azure.Extensions.AspNetCore.Configuration.Secrets package. Update appsettings.json with your Key Vault URL. Then, modify Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            var keyVaultEndpoint = new Uri(Environment.GetEnvironmentVariable("VaultUri"));
            config.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

4. Use secrets in your code

Inject IConfiguration into your classes. Access secrets with Configuration["SecretName"].

That's it! You're now using Azure Key Vault in your .NET Core app.

Related posts

Read more