How To Implement Azure Key Vault In .NET Core?

Keeping important information like API keys and passwords safe is crucial to ensure application security. Azure Key Vault offers a robust solution for storing and accessing secrets securely.
To start the process, you’ll need:
- Azure Subscription
- Azure Key Vault
- .NET Core SDK
Step-by-Step Process for Implementing Azure Key Vault in a .NET Core Application
Step 1: Create an Azure Key Vault
- Go to the Azure Portal. Then, click on Create a Resource> Security + Identity > Key Vault.
- Fill in the necessary details.
- Click Review + Create and then Create.
- Add secrets to the Key Vault.
Step 2: Set Up Your .NET Core Application
Create a .NET Core Project:
dotnet new console -n KeyVaultDemo
cd KeyVaultDemo
Add necessary NuGet Packages:
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets
Step 3: Configure Key Vault Access in Startup.cs
In your Startup.cs file, add configuration to use Azure Key Vault:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add Azure Key Vault Configuration
var keyVaultUrl = Configuration["KeyVaultUrl"];
var secretClient = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
// Example: Retrieve a secret
KeyVaultSecret secret = secretClient.GetSecret("your-secret-name");
services.AddControllers();
}
Step 4: Store Key Vault URL and Secrets in appsettings.json
Add your Key Vault URL and secrets in appsettings.json:
{
"KeyVaultUrl": "https://your-key-vault-name.vault.azure.net/",
"AllowedHosts": "*"
}
Step 5: Accessing Secrets in Your Controller
You can now inject SecretClient into your controllers or services to access secrets programmatically. Here’s an example:
public class ValuesController : ControllerBase
{
private readonly SecretClient _secretClient;
public ValuesController(SecretClient secretClient)
{
_secretClient = secretClient;
}
[HttpGet("secret")]
public async Task<ActionResult<string>> GetSecret()
{
KeyVaultSecret secret = await _secretClient.GetSecretAsync("your-secret-name");
return secret.Value;
}
}
Step 5: Run your .NET Core Web API Project.
Code Signing with Azure Key Vault
Leverage the Cloud Based Software Security by Securely Store your Private Key and Code Signing Certificate to Microsoft Azure Key Vault.
Get Azure Key Vault Code Signing Certificate