Published on

Securing Secrets With Azure Key Vault

5 min read
Authors
  • avatar
    Name
    Ivan Gechev
    Twitter

In this post, we'll take a look at another way of storing configuration information in .NET applications. We'll stray away from the well-known appsettings.json file and dive into the world of Azure and Azure Key Vault.

What Is Azure Key Vault

Azure Key Vault is a management solution in Azure for storing keys, secrets and certificates. It helps us centralize the storage of our application secrets, which brings numerous benefits. First and foremost, it allows us to have greater control over the distribution of these secrets. This means we can manage who has access to sensitive information more effectively and significantly reduce the risk of accidental leaks of our secrets. One of the great advantages for us as developers is that we no longer need to store security information directly within our code. This gives us peace of mind and helps maintain a higher level of security for our applications.

Accessing Azure Key Vault

To access a Key Vault, proper authentication and authorization are required. These measures are in place to ensure that only authorized users or applications can gain access. Authentication verifies the identity of the caller, while authorization defines what operations they are allowed to perform.

Before we start, we need to install two NuGet packages. We can use the .NET CLI:

CLI
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets

Or the Package Manager inside Visual Studio:

PackageManager
Install-Package Azure.Identity
Install-Package Azure.Security.KeyVault.Secrets

Once we have the packages installed, we can create our SecretService:

SecretService.cs
public class SecretService
{
    private readonly SecretClient _secretClient;

    public SecretService()
    {
        _secretClient = new SecretClient(
            new Uri("KeyVaultEndpoint"),
            new EnvironmentCredential());
    }
}

The entry point for the Azure Key Vault is a class called SecretClient. We create private readonly field for the SecretClient and initialize it in the constructor. The constructor of the SecretClient requires the following arguments - a Uri representing the Azure Key Vault endpoint and a TokenCredential. We will opt for the EnvironmentCredential, you can check how it works, as well as other options you can use here.

This is everything we need to start using the Azure Key Vault. Next, we will see how we can retrieve secrets.

Retrieving Secrets From Azure Key Vault

Fetching a secret is very easy:

SecretService.cs
public async Task<string> GetSecretAsync(string secretName)
{
    var secret = await _secretClient.GetSecretAsync(secretName);

    if (secret.HasValue)
    {
        return secret.Value.Value;
    }
    else
    {
        return "Secret was not found!";
    }
}

We create the GetSecretAsync method, which we can use to retrieve secrets asynchronously. It takes a string parameter called secretName, representing the name of the secret we want to retrieve from Azure Key Vault.

First, we call the _secretClient's GetSecretAsync method to retrieve the secret value associated with the provided secretName. The result of the async operation is stored in the secret variable. Since the method is asynchronous, we use the await keyword to await the completion of the operation. This allows other parts of the application to continue execution while waiting for the secret retrieval to complete.

Next, we check if the secret was successfully fetched, by using secret.HasValue. This is a property indicating whether the secret exists and has a valid value. If the secret has a value, the method returns the actual secret value using secret.Value.Value. Here, secret.Value represents a KeyVaultSecret object holding the secret name, value and other properties. The last .Value is used to extract the actual value from that object. If the secret does not have a value (which means it wasn't found or there was an error during retrieval), the method returns Secret was not found!.

And this was everything we need to do to retrieve secrets from Azure Key Vault!

Conclusion

By leveraging Azure Key Vault, we can simplify our security practices, enhance protection against data breaches, and make our application more robust overall. It's also very easy to do so and requires only a few lines of code. Now, we can rest assured that our sensitive information is in good hands!