Keeping Secrets Safe in .NET/ASP.NET Core Applications with Azure Key Vault

Introduction

Securing secrets in .NET/ASP.NET Core applications using Azure Key Vault is crucial for maintaining the confidentiality and integrity of sensitive information such as API keys, connection strings, and certificates. In this example, I'll walk you through the steps to integrate Azure Key Vault into an ASP.NET Core application to keep secrets safe in real time.

Prerequisites

  1. Visual Studio or Visual Studio Code (with .NET Core SDK installed).
  2. Azure subscription with an Azure Key Vault instance created.

Step 1. Set up an Azure Key Vault

  1. Log in to the Azure portal (https://portal.azure.com).
  2. Create a new Azure Key Vault instance.
  3. Note the Key Vault URI and access policies.


Step 2. Create an ASP.NET Core Application

  1. Open Visual Studio or Visual Studio Code and create a new ASP.NET Core web application.
  2. Step 3: Install the Required Packages
  3. In your project, you'll need to install the Azure SDK for Key Vault.
dotnet add package, Azure.Security.KeyVault.Secrets

Step 4. Configure AppSettings for Key Vault

In your appsettings.json, add a section for Azure Key Vault configuration.

{
  "AzureKeyVault": {
    "VaultUri": "YOUR_KEY_VAULT_URI"
  },
}

Replace YOUR_KEY_VAULT_URI with your Azure Key Vault URI.

Step 5. Configure Azure Key Vault Access

In your Startup.cs, add the following code to configure Azure Key Vault access.

using Azure.Identity;

Author: Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{
    
    // Add Key Vault client
    var keyVaultUri = Configuration.GetSection("AzureKeyVault:VaultUri").Value;
    services.AddSingleton(x => new SecretClient(new Uri(keyVaultUri), new DefaultAzureCredential()));
}

This code sets up a SecretClient using the DefaultAzureCredential, which automatically handles authentication using Azure AD credentials.

Step 6. Retrieve Secrets in the Controller

In your controller or service where you need to access secrets, inject the SecretClient and retrieve secrets.

using Azure.Security.KeyVault.Secrets;

Author: Sardar Mudassar Ali Khan
private readonly SecretClient _secretClient;

public MyController(SecretClient secretClient)
{
    _secretClient = secretClient;
}

public async Task<IActionResult> SecretAction()
{
    // Retrieve a secret from Key Vault
    string secretName = "AzureSecret";
    KeyVaultSecret secret = await _secretClient.GetSecretAsync(secretName);

    // Use the secret's value
    string secretValue = secret.Value;

}

Make sure to replace "MySecretName" with the name of the secret you want to access.

Step 7: Run and Test

  1. Run your ASP.NET Core application, and it will securely access secrets from Azure Key Vault in real-time.
  2. Remember to manage access policies and authentication for your Azure Key Vault instance to ensure proper security.
  3. By following these steps, you can keep secrets safe in your .NET/ASP.NET Core applications using Azure Key Vault, providing a secure and scalable way to manage sensitive information.

How to use in Application?

To use secrets from Azure Key Vault in your ASP.NET Core application, you typically need to access and utilize those secrets within your application's code. Here's how you can use secrets retrieved from Azure Key Vault within your application:

Assuming you've already set up Azure Key Vault integration, as mentioned in the previous answer:

Step 1. Retrieve the Secret

You can retrieve a secret from Azure Key Vault using the SecretClient, as shown in the previous example. Make sure the SecretClient is injected into your controller or service.

using Azure.Security.KeyVault.Secrets;

Author: Sardar Mudassar Ali Khan
private readonly SecretClient _secretClient;

public MyController(SecretClient secretClient)
{
    _secretClient = secretClient;
}

public async Task<IActionResult> SecretAction()
{
    string secretName = "AzureSecret";
    KeyVaultSecret secret = await _secretClient.GetSecretAsync(secretName);

    // Use the secret's value
    string secretValue = secret.Value;
}

Step 2. Use the Secret

Once you have retrieved the secret, you can use it in your application as needed. For example, you might use it to establish a database connection, authenticate with an external service, or perform other secure operations.

Author: Sardar Mudassar Ali Khan
public async Task<IActionResult> SecretAction()
{
    string secretName = "AzureSecret";
    KeyVaultSecret secret = await _secretClient.GetSecretAsync(secretName);

    // Use the secret's value
    string secretValue = secret.Value;

    // Use the secret in your application logic
    // For example, set up a database connection using the secret
    var connectionString = $"Server=your_server;Database=your_database;User Id=your_user;Password={secretValue};";
    
}

In this example, the secret retrieved from Azure Key Vault is used to construct a database connection string securely.

Step 3. Ensure Proper Error Handling

When accessing secrets from Azure Key Vault, it's essential to handle exceptions properly. The SecretClient can throw exceptions if there are issues with authentication or secret retrieval. Make sure to implement error handling to manage these situations gracefully.

Author: Sardar Mudassar Ali Khan
public async Task<IActionResult> SecretAction()
{
    try
    {
        string secretName = "AzureSecret";
        KeyVaultSecret secret = await _secretClient.GetSecretAsync(secretName);

        // Use the secret's value
        string secretValue = secret.Value;

        // Use the secret in your application logic
        // ...

        return Ok("Operation completed successfully.");
    }
    catch (RequestFailedException ex)
    {
        // Handle the exception (e.g., log, return an error response)
        return StatusCode((int)ex. Status, "Failed to retrieve a secret from Key Vault: " + 
      ex.Message);
    }
}

By following these steps, you can securely use secrets from Azure Key Vault within your ASP.NET Core application while handling exceptions and ensuring proper error handling.

Conclusion

Integrating Azure Key Vault into your ASP.NET Core application allows you to securely manage and use sensitive secrets and configuration settings. Here's a summary of the key steps and concepts.

1. Set Up Azure Key Vault

  1.    Create an Azure Key Vault instance in your Azure subscription.
  2.    Configure access policies and permissions for your Key Vault.

2. Configure Your ASP.NET Core Application

  1.   Add the Azure SDK package for Key Vault to your project.
  2.    Configure the Key Vault URI in your application's appsettings.json or through environment variables.

3. Access Secrets

  1.    Create a SecretClient in your application to interact with Azure Key Vault.
  2.    Retrieve secrets from the Key Vault using the GetSecretAsync method.
  3.    Use the retrieved secrets in your application's logic, such as establishing secure connections to databases or external services.

4. Error Handling

  1.   Implement proper error handling to manage exceptions that may occur during secret retrieval from the Key Vault. Handle exceptions like RequestFailedException gracefully and log or respond to them accordingly.

By following these steps and best practices, you can enhance the security of your ASP.NET Core application by centralizing and protecting sensitive information in Azure Key Vault. This approach ensures that secrets are securely managed, rotated, and audited, contributing to the overall security and compliance of your application.


Similar Articles