AZURE KEY VAULT INTEGRATION IN .NET CORE APPLICATIONS

Securing .NET Core Applications with Azure Key Vault

Secure Your Secrets with Azure Key Vault: A Comprehensive Guide

Jiyan Epözdemir
Dev Genius
Published in
7 min readApr 12, 2024

--

Securing sensitive information, such as API keys, connection strings, and other secrets, is very important for software development. Database credentials, API keys, or access information are necessary while designing an application in order to communicate with other components, and this sensitive data is often hard coded in configuration files or the code itself. It may result with security breaches when someone leaves the team, the server or source codes are compromised, or unauthorized users get access to that kind of secret data.

There are many methods available to avoid this. Today, we’ll look at how we can use Microsoft’s Azure Key Vault service to increase the security of our sensitive data. Azure Key Vault provides a robust and scalable solution for managing and safeguarding these secrets.

In this blog post, we’ll explore how to integrate Azure Key Vault into a .NET Core API project, ensuring a more secure and manageable approach to handling sensitive data.

What is Azure?

Azure is a cloud computing platform and set of services offered by Microsoft. It provides a wide range of cloud-based services, including computing, storage, networking, databases, analytics, machine learning, artificial intelligence (AI), Internet of Things (IoT), and more. Azure allows businesses to build, deploy, and manage applications and services through Microsoft’s global network of data centers.

What is Azure Key Vault?

Azure Key Vault is a cloud service provided by Microsoft Azure that allows you to securely store and manage sensitive information such as cryptographic keys, passwords, certificates, and other secrets. It helps you safeguard your keys and secrets by using hardware security modules (HSMs) to protect cryptographic keys and by adhering to industry best practices for security.

Some key features and benefits of Azure Key Vault include:

  • Secure Key Management: It provides a secure repository for storing cryptographic keys, which are essential for encrypting and decrypting data.
  • Secrets Management: You can securely store and manage application secrets, such as connection strings, API keys, and passwords, reducing the risk of exposure.
  • Centralized Management: Azure Key Vault allows you to centralize the management of keys and secrets across your applications and services, providing a single, secure location for sensitive information.
  • Integration with Azure Services: It seamlessly integrates with other Azure services, such as Azure Virtual Machines, Azure App Service, Azure Functions, and Azure Kubernetes Service, making it easy to incorporate strong security measures into your applications and workflows.
  • Role-Based Access Control (RBAC): Azure Key Vault supports RBAC, allowing you to control access to keys and secrets based on the roles assigned to users and applications.
  • Auditing and Logging: It provides comprehensive logging and auditing capabilities, enabling you to track access to keys and secrets and monitor for suspicious activity.

Overall, Azure Key Vault helps organizations enhance the security of their applications and data by providing a robust, scalable, and easy-to-use solution for managing cryptographic keys and secrets in the cloud.

Getting Started with Azure Key Vault

Step 1 : Go to the Azure portal at https://portal.azure.com and sign in with your Azure account credentials.

Step 2 : Once you’re logged in, you’ll be in the Azure Portal dashboard. Use the search bar at the top to find “Key Vaults” or navigate to it through the left-hand menu under “All services” > “Security + Identity” > “Key Vaults”.

Step 3 : In the Key Vaults blade, click the “+ Add” button to create a new Key Vault.

Step 4 : Configure Key Vault settings:

  • Subscription: Choose the Azure subscription you want to use.
  • Resource group: Either create a new resource group or select an existing one. Resource groups are containers that hold related Azure resources for management and billing purposes.
  • Key vault name: Enter a unique name for your Key Vault. This name will be used in the Key Vault URI.
  • Region: Select the Azure region where you want to deploy your Key Vault. Choose a region close to your applications for better performance.
  • Pricing tier: Choose the pricing tier based on your requirements. The pricing tier determines the performance and capabilities of your Key Vault.
  • Access policies: Configure access policies to specify who has permissions to manage and use the keys and secrets stored in the Key Vault.

Step 5 : Review your settings to ensure everything is configured correctly. Once you’re satisfied, click the “Create” button to create your Key Vault.

That’s it! You’ve successfully created an Azure Key Vault.

Azure will now deploy your Key Vault. This process usually takes a few seconds to a minute. You can monitor the deployment progress in the Azure Portal.

Once the deployment is complete, you can access your Key Vault from the Azure Portal. Navigate back to the Key Vaults blade, and you should see your newly created Key Vault listed there.

You can now start using your Key Vault to store and manage cryptographic keys, secrets, and certificates securely. Creating a secret in Azure Key Vault is a also quite simple process.

Let’s create a “SqlConnectionString” secret in newly created Azure Key Vault.

Step 1 : Navigate back to the Key Vaults blade, and select the “Secrets” option from the left-hand menu.

Step 2 : Click the “+ Generate/Import” button to add a new secret to your Key Vault.

Step 3 : Configure the secret:

  • Upload options: You can choose to manually enter the secret value or upload a secret from a file.
  • Name: Enter a name for your secret. This name should be unique within the Key Vault.
  • Value: Enter the value of your secret. This could be anything from a password, API key, connection string, or any other sensitive information.
  • Content type: Optionally, you can specify the content type of your secret, such as text/plain or application/json.

Advanced settings (optional):

  • Activation date: Specify the date when the secret becomes valid.
  • Expiration date: Specify the date when the secret expires and should no longer be used.
  • Not before: Specify the date when the secret becomes usable.

Step 4 : Review your settings to ensure everything is configured correctly. Once you’re satisfied, click the “Create” button to add the secret to your Key Vault.

Azure will now deploy your secret to the Key Vault. This process usually takes a few seconds to a minute.

Once the deployment is complete, you can access your secret from the Secrets blade in your Key Vault. You can view, update, or delete the secret as needed.

That’s it! We’ve successfully created a secret in Azure Key Vault. Now, create a sample project to demonstrate accessing secrets in newly created Key Vault.

Creating a Sample .NET Core API Project

Step 1 : Open your terminal or command prompt and run the following command to create a new .NET Core API project:

dotnet new webapi -n AzureVaultSampleApi

Navigate to the newly created project directory:

cd AzureVaultSampleApi

Step 2 : Install the necessary NuGet packages for integrating Azure Key Vault:

dotnet add package Microsoft.Extensions.Configuration.AzureKeyVault

Step 3: Update the appsettings.json file with your Azure Key Vault URI:

{
"AzureKeyVault": {
"Name": "azurekeyvaultjepozdemir",
"ClientId": "YOUR_KEY_VAULT_CLIENT_ID",
"ClientSecret": "YOUR_KEY_VAULT_CLIENT_SECRET"
}
}

Step 4 : Open the Program.cs file and modify it to include Azure Key Vault in the configuration root:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace AzureVaultSampleApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((ctx, config) =>
{
var root = config.Build();
config.AddAzureKeyVault(
$"https://{root["AzureKeyVault:Name"]}.vault.azure.net/",
root["AzureKeyVault:ClientId"],
root["AzureKeyVault:ClientSecret"]);
});
}
}

You can now access the Azure Key Vault secrets in your controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace AzureVaultSampleApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
private readonly IConfiguration _configuration;

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

[HttpGet]
public IActionResult GetConnectionString()
{
var connectionString = _configuration["SqlConnectionString"];
return Ok(new { ConnectionString = connectionString });
}
}
}

Finally, run your .NET Core API project:

dotnet run

Your API should now be running, and you can access the /sample endpoint to retrieve the secret value from Azure Key Vault.

By following these steps, you have successfully created a .NET Core API project that integrates Azure Key Vault for secure secret management. This serves as a foundation for building more secure and scalable applications in the future.

Conclusion

By incorporating Azure Key Vault into your .NET Core application, you enhance security and simplify secret management. This approach not only protects sensitive data but also streamlines the process of updating or rotating secrets, providing a scalable solution for modern applications.

Feel free to explore additional features and capabilities offered by Azure Key Vault to further enhance the security posture of your applications. As technology evolves, embracing robust security practices becomes increasingly vital, and Azure Key Vault is an excellent tool to achieve that goal in the .NET Core ecosystem.

Sample codes used here are available in the following GitHub repository:

Thank you for reading!

If you found this post helpful, don’t forget to give it a clap and share it with others who might benefit from it.👏👏👏👏👏

--

--

I am a multi-disciplined Software Architect and Computer Engineer, MSc. I enjoy building awesome softwares & applications.