Edit

Tutorial: Use Azure Key Vault with a virtual machine in .NET

Azure Key Vault helps you protect secrets such as API keys and database connection strings that your applications, services, and resources need.

In this tutorial, you configure a console application to read information from Azure Key Vault. The application uses the VM's managed identity to authenticate to Key Vault.

The tutorial shows you how to:

  • Create a resource group.
  • Create a key vault.
  • Add a secret to the key vault.
  • Retrieve a secret from the key vault.
  • Create an Azure virtual machine.
  • Enable a managed identity for the Virtual Machine.
  • Assign permissions to the VM identity.

Before you begin, read Key Vault basic concepts.

If you don't have an Azure subscription, create a free account.

Prerequisites

For Windows, Mac, and Linux:

Create resources and assign permissions

Before you start coding you need to create some resources, put a secret into your key vault, and assign permissions.

Sign in to Azure

Sign in to Azure with the Azure CLI or Azure PowerShell:

az login

Create a resource group and key vault

This quickstart uses a precreated Azure key vault. You can create a key vault by following the steps in these quickstarts:

Alternatively, you can run these Azure CLI or Azure PowerShell commands.

Important

Each key vault must have a unique name. Replace <vault-name> with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<vault-name>" -g "myResourceGroup" --enable-rbac-authorization true

Populate your key vault with a secret

Let's create a secret called mySecret, with a value of Success!. A secret might be a password, a SQL connection string, or any other information that you need to keep both secure and available to your application.

To add a secret to your newly created key vault, use the following command:

az keyvault secret set --vault-name "<vault-name>" --name "mySecret" --value "Success!"

Create a virtual machine

Create a Windows or Linux VM by using one of the following methods:

Windows Linux
Azure CLI Azure CLI
PowerShell PowerShell
Azure portal Azure portal

Assign an identity to the VM

Create a system-assigned managed identity for the VM:

az vm identity assign --name <vm-name> --resource-group <resource-group>

Note the system-assigned identity that's displayed in the following code. The output of the preceding command would be:

{
  "systemAssignedIdentity": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "userAssignedIdentities": {}
}

Assign permissions to the VM identity

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

az role assignment create --role "Key Vault Secrets User" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/<vault-name>"

Replace <upn>, <subscription-id>, and <vault-name> with your actual values. If you used a different resource group name, replace "myResourceGroup" as well. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Sign in to the VM

To sign in to the VM, follow the instructions in Connect and sign in to an Azure Windows virtual machine or Connect and sign in to an Azure Linux virtual machine.

Set up the console app

Create a console app and install the required packages with the dotnet command.

Install .NET

To install .NET, go to the .NET downloads page.

Create and run a sample .NET app

Open a command prompt and run:

dotnet new console -n keyvault-console-app
cd keyvault-console-app
dotnet run

The app prints "Hello World" to the console.

Install the packages

From the console window, install the Azure Key Vault Secrets client library and Azure Identity library:

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

Edit the console app

Open Program.cs and add the following using directives:

using System;
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

Replace the Main method with the following code, updating <vault-name> to your key vault name. This code uses DefaultAzureCredential to authenticate to Key Vault, which uses a token from the VM's managed identity. It also configures exponential backoff for retries in case Key Vault is throttled.

  class Program
    {
        static void Main(string[] args)
        {
            string secretName = "mySecret";
            string keyVaultName = "<vault-name>";
            var kvUri = "https://<vault-name>.vault.azure.net";
            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                {
                    Delay= TimeSpan.FromSeconds(2),
                    MaxDelay = TimeSpan.FromSeconds(16),
                    MaxRetries = 5,
                    Mode = RetryMode.Exponential
                 }
            };

            var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential(),options);

            Console.Write("Input the value of your secret > ");
            string secretValue = Console.ReadLine();

            Console.Write("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "' ...");

            client.SetSecret(secretName, secretValue);

            Console.WriteLine(" done.");

            Console.WriteLine("Forgetting your secret.");
            secretValue = "";
            Console.WriteLine("Your secret is '" + secretValue + "'.");

            Console.WriteLine("Retrieving your secret from " + keyVaultName + ".");

            KeyVaultSecret secret = client.GetSecret(secretName);

            Console.WriteLine("Your secret is '" + secret.Value + "'.");

            Console.Write("Deleting your secret from " + keyVaultName + " ...");

            client.StartDeleteSecret(secretName);

            System.Threading.Thread.Sleep(5000);
            Console.WriteLine(" done.");

        }
    }

Clean up resources

When you no longer need them, delete the VM and the key vault.

Next steps