How to work with Azure Key Vault in .NET Core

Azure Key Vault is a safe and secure place to store the tokens, keys, passwords, certificates, and other sensitive data used in your .NET Core applications. Here’s how to work with it in C#.

Black and white heavy duty bank vault
Thinkstock

When building .NET Core applications, we often make use of various “secrets” such as client IDs, access tokens, passwords, certificates, encryption keys, and API keys. Naturally, we need a secure way to store, manage, and control access to this sensitive data. Azure Key Vault provides a handy, cloud-based solution for this.

In this article, we’ll examine how we can work with Azure Key Vault in C#. To follow along with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you would like to use.
  8. Click Create.

We’ll use this .NET 7 console application project to work with Azure Key Vault in the subsequent sections of this article.

What is Azure Key Vault?

Azure Key Vault is a cloud-based, secure storage solution that safeguards your application’s secrets or other sensitive data pertaining to your application. Such secrets might be tokens, keys, IDs, passwords, certificates, etc. Azure Key Vault provides a safe, secure, centralized store for secrets, along with strong access controls, eliminating the need for developers to directly manage sensitive data within their applications.

In the sections that follow, we will create a Key Vault, create some secrets, and then read and delete these secrets programmatically.

Create a key vault in Azure

To create a key vault in Azure, follow the steps outlined below.

  1. From the Azure Portal menu or the Home page, select “Create a resource.”
  2. Select Key Vault from the list of the resources displayed.
  3. Click Create.
  4. In the “Create a key vault” screen, specify the subscription, resource group name, region, and pricing tier and leave the other options to their default values.
  5. Click “Review + Create”
  6. Review the details entered and then click Create.

Create an app secret in your Azure key vault

Next, you should add a secret to the key vault instance created in the preceding section. To do this, follow the steps outlined below.

  1. Select Secrets from the Key Vault configuration page.
  2. Click Generate/Import to add a secret to the key vault.
  3. Select Manual (the default) from the “Upload options” drop-down menu.
  4. Specify the name and value of the secret.
  5. Optionally specify the content type, activation date, and expiration date.
  6. Click Create.

Add roles to access your key vault

To provide access to the secret we created, follow the steps listed below.

  1. Select “Access control (IAM)” from the Key Vault screen.
  2. Click “Add role assignment.”
  3. Select the role you would like to assign from the list of roles displayed.
  4. Assign access to either “Managed identity” or “User, group, or service principal.”
  5. Select members to whom the role will be assigned.
  6. Optionally, specify the description of the role.
  7. Click Next.
  8. Click “Review + assign.”

Read data from the Azure key vault

Next we create an instance of the DefaultAzureCredential class and pass it as an argument to the SecretClient class. This creates a secret client we can use to connect to and work with Azure Key Vault. When creating an instance of SecretClient, you also should specify the KeyVault URI as shown in the code snippet given below.

var credentials = new DefaultAzureCredential();
azureKeyVaultSecretClient = new SecretClient(new
Uri(KeyVaultUri), credentials);

Here is the complete code listing for your reference.

    class Program
    {
        const string KeyVaultName = "AzureKeyValueExample";
        const string KeyVaultUri = $ https://{KeyVaultName}.vault.azure.net";
        static SecretClient ? azureKeyVaultSecretClient;
        static void Main(string[] args)
        {
            var credentials = new DefaultAzureCredential();
            azureKeyVaultSecretClient = new SecretClient(new
            Uri(KeyVaultUri), credentials);
            Console.WriteLine("Displaying all secrets with their values:");
            var azureKeyVaultSecrets =
            azureKeyVaultSecretClient.GetPropertiesOfSecrets();
            foreach(var secret in azureKeyVaultSecrets)
            {
                var secretValue =
                azureKeyVaultSecretClient.GetSecret(secret.Name);
                Console.WriteLine($ "{secret.Name} |
                {secretValue.Value.Value} |
                {secretValue.Value.Properties.ContentType}");
            }
            Console.Read();
        }
    }
azure key vault display secrets 01 IDG

Figure 1. When you execute the above program in the console window, it will display your secrets and their values.

Create a new secret in the Azure key vault

You can use the following piece of code to create a new secret and assign it a value in your key vault instance.

string secretName = "NewSecret";
string secretValue = "NewSecretValue";
await azureKeyVaultSecretClient.SetSecretAsync(secretName, secretValue);
var secret = azureKeyVaultSecretClient.GetSecret(secretName);
Console.WriteLine($ "{secretName} created with value {secretValue}");

You can see the new secret created in the Azure portal as shown in Figure 2 below.

azure key vault display secrets 02 IDG

Figure 2. Our new secret displayed in the Key Vault screen of the Azure portal.

Delete a secret from the Azure key vault

The StartDeleteSecret method of the SecretClient class deletes a secret from the Azure Key Vault. You just need to pass the name of the secret you would like to delete as a parameter to this method, as shown in the code snippet below.

string secretNameForDelete = "NewSecret";
var deleteOperation = azureKeyVaultSecretClient.StartDeleteSecret(secretNameForDelete);
Console.WriteLine($"Deleting secret {secretNameForDelete} from Key Vault");
while (!deleteOperation.HasCompleted)
{
     Thread.Sleep(500);
     deleteOperation.UpdateStatus();
}
Console.WriteLine($"Secret {secretNameForDelete} deleted from Key Vault");
Console.Read();

If you now browse the Key Vault screen in the Azure portal, you will see that the secret has been deleted.

Conclusion

When you execute the program, you might encounter an Azure.Identity.CredentialUnavailableException. To solve this, from within the Visual Studio IDE, click on Tools -> Options -> Azure Service Authentication. Ensure that you’re signed in using your Azure account credentials.

With Azure Key Vault, you can centrally manage keys and secrets, improve application security and industry compliance, and simplify the management and protection of sensitive data.

Copyright © 2023 IDG Communications, Inc.

How to choose a low-code development platform