medium.com 4 min read Original Source

Building More Secure C# .NET Applications with HashiCorp Vault

Have you ever found yourself hardcoding database passwords or API keys directly in your _appsettings.json_ file? If you’re nodding your head right now, you’re definitely not alone. This is one of those common practices that we all know is wrong, but somehow we keep doing it anyway — especially when we’re in a hurry to get things working.

The problem is clear: sensitive information like connection strings, API tokens, and passwords shouldn’t be sitting in configuration files that might end up in version control. Even if you’re careful, accidents happen. Someone might commit a file they shouldn’t, or a configuration file might get exposed during deployment.

This is where HashiCorp Vault comes into play. Vault is a powerful tool designed to store and manage secrets securely. Think of it as a secure vault (pun intended) where you can store all your sensitive data, and your applications can access it when needed — without ever storing secrets in your codebase.

In this article, I’ll show you how to set up Vault with Consul (its storage backend) using Docker, and then integrate it seamlessly into your ASP.NET Core application using the familiar _IConfiguration_ interface. The best part? Your code will look almost exactly the same as when you’re reading from _appsettings.json_, but your secrets will be stored securely in Vault.

Setting Up Vault with Consul Using Docker

Getting started with Vault is surprisingly straightforward, especially with Docker. We’ll use Docker Compose to run both Vault and Consul together. Consul acts as the storage backend for Vault, which means Vault will store all its data in Consul.

Here’s a simple _docker-compose.yml_ file that sets up everything you need:

version: '3.8'

services:
  consul:
    image: hashicorp/consul:latest
    container_name: consul
    command: consul agent -server -bootstrap -ui -client=0.0.0.0 -bind=0.0.0.0 -data-dir=/consul/data -node=consul-1
    ports:
      - "8500:8500"
    networks:
      - vault-network

  vault:
    image: hashicorp/vault:latest
    container_name: vault
    ports:
      - "8200:8200"
    volumes:
      - ./vault-config:/vault/config
    cap_add:
      - IPC_LOCK
    command: vault server -config=/vault/config/vault.hcl
    networks:
      - vault-network
    depends_on:
      consul:
        condition: service_healthy
version: '3.8'

services:
  consul:
    image: hashicorp/consul:latest
    container_name: consul
    command: consul agent -server -bootstrap -ui -client=0.0.0.0 -bind=0.0.0.0 -data-dir=/consul/data -node=consul-1
    ports:
      - "8500:8500"
    networks:
      - vault-network

  vault:
    image: hashicorp/vault:latest
    container_name: vault
    ports:
      - "8200:8200"
    volumes:
      - ./vault-config:/vault/config
    cap_add:
      - IPC_LOCK
    command: vault server -config=/vault/config/vault.hcl
    networks:
      - vault-network
    depends_on:
      consul:
        condition: service_healthy

This setup gives you a single-node Vault instance with Consul as the storage backend. For production environments, you’d want to set up a Vault cluster with multiple nodes for high availability, but for development and learning purposes, this single-node setup works perfectly.

To start everything up, just run:

docker-compose up -d

Once Vault is running, you’ll need to initialize it and unseal it. Initialization generates the unseal keys and root token, while unsealing makes Vault operational. You can do this with:

<button data-code="docker exec -it vault vault operator init -key-shares=5 -key-threshold=2
docker exec -it vault vault operator unseal
docker exec -it vault vault operator unseal
docker exec -it vault vault operator unseal ” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

docker exec -it vault vault operator init -key-shares=5 -key-threshold=2
docker exec -it vault vault operator unseal <KEY1>
docker exec -it vault vault operator unseal <KEY2>
docker exec -it vault vault operator unseal <KEY3>
docker exec -it vault vault operator init -key-shares=5 -key-threshold=2
docker exec -it vault vault operator unseal <KEY1>
docker exec -it vault vault operator unseal <KEY2>
docker exec -it vault vault operator unseal <KEY3>

Now you’re ready to store secrets! Let’s add a simple secret:

docker exec -it vault vault kv put kv/dotnet username=admin password=secret123
docker exec -it vault vault kv put kv/dotnet username=admin password=secret123

Of course you can use UI for storing your secrets, but you must know that you can only access unsealed vaults via UI and do not lose your root_token that was given by the first initialization step. The root token is your master key to Vault, and losing it means you’ll need to reinitialize everything, which also means losing all your stored secrets. So keep it safe, preferably in a password manager or a secure key store.

Storing Vault Credentials in Environment Variables

One of the key security practices when working with Vault is to never hardcode your Vault address or authentication token in your application code. Instead, we should use environment variables. This way, different environments (development, staging, production) can use different Vault instances and tokens without changing any code.

In your ASP.NET Core application, you can read these environment variables like this:

var vaultAddress = Environment.GetEnvironmentVariable("VAULT_ADDR");
var vaultToken = Environment.GetEnvironmentVariable("VAULT_TOKEN");
var vaultAddress = Environment.GetEnvironmentVariable("VAULT_ADDR");
var vaultToken = Environment.GetEnvironmentVariable("VAULT_TOKEN");

Setting environment variables depends on your operating system:

//Windows PowerShell
$env:VAULT_ADDR="http://localhost:8200"
$env:VAULT_TOKEN="your-vault-token-here"

//Linux or Mac
export VAULT_ADDR="http://localhost:8200"
export VAULT_TOKEN="your-vault-token-here"
//Windows PowerShell
$env:VAULT_ADDR="http://localhost:8200"
$env:VAULT_TOKEN="your-vault-token-here"

//Linux or Mac
export VAULT_ADDR="http://localhost:8200"
export VAULT_TOKEN="your-vault-token-here"

This approach gives you flexibility. Your development environment might point to a local Vault instance, while your production environment uses a completely different Vault server. The code stays the same; only the environment variables change.

Reading Vault Secrets with IConfiguration in ASP.NET Core

Now comes the interesting part — integrating Vault with your ASP.NET Core application. The goal is to make Vault secrets accessible through the same _IConfiguration_ interface you’re already using for _appsettings.json_. This means your existing code doesn’t need to change much.

To achieve this, we need to create a custom configuration provider. Here’s how it works:

First, we create a _VaultConfigurationProvider_ that extends _ConfigurationProvider_:

public class VaultConfigurationProvider : ConfigurationProvider
{
    private readonly string _vaultAddress;
    private readonly string _vaultToken;
    private readonly string _secretPath;
    private readonly string _mountPoint;

    public VaultConfigurationProvider(string vaultAddress, string vaultToken,
        string secretPath, string mountPoint = "kv")
    {
        _vaultAddress = vaultAddress;
        _vaultToken = vaultToken;
        _secretPath = secretPath;
        _mountPoint = mountPoint;
    }

    public override void Load()
    {
        var authMethodInfo = new TokenAuthMethodInfo(_vaultToken);
        var vaultClientSettings = new VaultClientSettings(_vaultAddress, authMethodInfo);
        var vaultClient = new VaultClient(vaultClientSettings);

        // Try KV v2 first, fall back to v1 if needed
        var secretV2 = vaultClient.V1.Secrets.KeyValue.V2
            .ReadSecretAsync(path: _secretPath, mountPoint: _mountPoint)
            .GetAwaiter().GetResult();

        if (secretV2?.Data?.Data != null)
        {
            foreach (var kvp in secretV2.Data.Data)
            {
                Data[kvp.Key] = kvp.Value?.ToString();
            }
        }
    }
}
public class VaultConfigurationProvider : ConfigurationProvider
{
    private readonly string _vaultAddress;
    private readonly string _vaultToken;
    private readonly string _secretPath;
    private readonly string _mountPoint;

    public VaultConfigurationProvider(string vaultAddress, string vaultToken,
        string secretPath, string mountPoint = "kv")
    {
        _vaultAddress = vaultAddress;
        _vaultToken = vaultToken;
        _secretPath = secretPath;
        _mountPoint = mountPoint;
    }

    public override void Load()
    {
        var authMethodInfo = new TokenAuthMethodInfo(_vaultToken);
        var vaultClientSettings = new VaultClientSettings(_vaultAddress, authMethodInfo);
        var vaultClient = new VaultClient(vaultClientSettings);

        // Try KV v2 first, fall back to v1 if needed
        var secretV2 = vaultClient.V1.Secrets.KeyValue.V2
            .ReadSecretAsync(path: _secretPath, mountPoint: _mountPoint)
            .GetAwaiter().GetResult();

        if (secretV2?.Data?.Data != null)
        {
            foreach (var kvp in secretV2.Data.Data)
            {
                Data[kvp.Key] = kvp.Value?.ToString();
            }
        }
    }
}

Then, in your _Program.cs_, you add this provider to your configuration builder:

var builder = WebApplication.CreateBuilder(args);

var vaultAddress = Environment.GetEnvironmentVariable("VAULT_ADDR");
var vaultToken = Environment.GetEnvironmentVariable("VAULT_TOKEN");

builder.Configuration.AddVaultConfiguration(vaultAddress, vaultToken, "dotnet", "kv");

builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
var builder = WebApplication.CreateBuilder(args);

var vaultAddress = Environment.GetEnvironmentVariable("VAULT_ADDR");
var vaultToken = Environment.GetEnvironmentVariable("VAULT_TOKEN");

builder.Configuration.AddVaultConfiguration(vaultAddress, vaultToken, "dotnet", "kv");

builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();

That’s it! Now you can use IConfiguration exactly as you normally would:

[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
    private readonly IConfiguration _configuration;

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

    [HttpGet]
    public IActionResult Get()
    {
        var username = _configuration["username"];
        var password = _configuration["password"];

        return Ok(new { username, password });
    }
}
[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
    private readonly IConfiguration _configuration;

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

    [HttpGet]
    public IActionResult Get()
    {
        var username = _configuration["username"];
        var password = _configuration["password"];

        return Ok(new { username, password });
    }
}

The magic here is that **__configuration["username"]_** and **__configuration["password"]_** are now reading from Vault, not from _appsettings.json_. Your code doesn’t know the difference, and that’s exactly what we want.

Conclusion

Integrating HashiCorp Vault with your ASP.NET Core applications doesn’t have to be complicated. By creating a custom configuration provider, you can make Vault secrets accessible through the same _IConfiguration_ interface you’re already familiar with. This means minimal changes to your existing code while significantly improving your security posture.

The key takeaways are:

  • Never hardcode secrets in your configuration files or code
  • Use environment variables for Vault connection details
  • Leverage IConfiguration to keep your code clean and consistent
  • Start simple with a single-node setup, then scale to clusters when needed

Remember, security is not a one-time thing. It’s an ongoing process. Using Vault is a great step toward better security practices, but it’s just one piece of the puzzle. Make sure you’re also following other security best practices like using HTTPS, implementing proper authentication and authorization, and regularly rotating your secrets.

If you’re new to Vault, start with this simple setup and experiment with it. Once you’re comfortable, you can explore more advanced features like dynamic secrets, secret rotation, and audit logging. The important thing is to start somewhere, and this setup gives you a solid foundation to build upon.

One final thought: if you’re using AI coding assistants, be aware that they can make mistakes and some of your information might get exposed along with the code. By using systems like Vault, you can make your applications more secure and protect sensitive data even if it accidentally ends up in your codebase.

Happy coding, and stay secure!