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#. Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Next. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you would like to use. 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. From the Azure Portal menu or the Home page, select “Create a resource.” Select Key Vault from the list of the resources displayed. Click Create. 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. Click “Review + Create” 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. Select Secrets from the Key Vault configuration page. Click Generate/Import to add a secret to the key vault. Select Manual (the default) from the “Upload options” drop-down menu. Specify the name and value of the secret. Optionally specify the content type, activation date, and expiration date. Click Create. Add roles to access your key vault To provide access to the secret we created, follow the steps listed below. Select “Access control (IAM)” from the Key Vault screen. Click “Add role assignment.” Select the role you would like to assign from the list of roles displayed. Assign access to either “Managed identity” or “User, group, or service principal.” Select members to whom the role will be assigned. Optionally, specify the description of the role. Click Next. 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(); } } 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. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos