Quickstart: Azure Key Vault client library for .NET (SDK v4)

Get started with the Azure Key Vault client library for .NET. Follow the steps below to install the package and try out example code for basic tasks.

Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. Use the Key Vault client library for .NET to:

  • Increase security and control over keys and passwords.
  • Create and import encryption keys in minutes.
  • Reduce latency with cloud scale and global redundancy.
  • Simplify and automate tasks for SSL/TLS certificates.
  • Use FIPS 140-2 Level 2 validated HSMs.

API reference documentation | Library source code | Package (NuGet)

Prerequisites

This quickstart assumes you are running dotnet, Azure CLI, and Windows commands in a Windows terminal (such as PowerShell Core, Windows PowerShell, or the Azure Cloud Shell).

Setting up

Create new .NET console app

Create a new .NET Core application in your preferred editor or IDE.

In a console window, use the dotnet new command to create a new console app with the name akv-dotnet.

dotnet new console -n key-vault-console-app

Change your directory to the newly created app folder. You can build the application with:

dotnet build

The build output should contain no warnings or errors.

Build succeeded.
 0 Warning(s)
 0 Error(s)

Install the package

From the console window, install the Azure Key Vault client library for .NET:

dotnet add package Azure.Security.KeyVault.Secrets --version 4.0.0

For this quickstart, you will need to install the following packages as well:

dotnet add package Azure.Identity --version 1.0.0

Create a resource group and key vault

This quickstart uses a pre-created Azure key vault. You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart. Alternatively, you can simply run the Azure CLI commands below.

Important

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

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

az keyvault create --name <your-unique-keyvault-name> -g "myResourceGroup"

Create a service principal

The simplest way to authenticate an cloud-based .NET application is with a managed identity; see Use an App Service managed identity to access Azure Key Vault for details. For the sake of simplicity however, this quickstarts creates a .NET console application. Authenticating a desktop application with Azure requires the use of a service principal and an access control policy.

Create a service principle using the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://mySP" --sdk-auth

This operation will return a series of key / value pairs.

{
  "clientId": "7da18cae-779c-41fc-992e-0527854c6583",
  "clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
  "subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
  "tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
  "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
  "resourceManagerEndpointUrl": "https://management.azure.com/",
  "activeDirectoryGraphResourceId": "https://graph.windows.net/",
  "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
  "galleryEndpointUrl": "https://gallery.azure.com/",
  "managementEndpointUrl": "https://management.core.windows.net/"
}

Take note of the clientId, clientSecret, and tenantId, as we will use them in the following steps.

Give the service principal access to your key vault

Create an access policy for your key vault that grants permission to your service principal by passing the clientId to the az keyvault set-policy command. Give the service principal get, list, and set permissions for both keys and secrets.

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --secret-permissions delete get list set --key-permissions create decrypt delete encrypt get list unwrapKey wrapKey

Set environmental variables

The DefaultAzureCredential method in our application relies on three environmental variables: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. use set these variables to the clientId, clientSecret, and tenantId values you noted in the Create a service principal step, above.

You will also need to save your key vault name as an environment variable called KEY_VAULT_NAME;

setx AZURE_CLIENT_ID <your-clientID>

setx AZURE_CLIENT_SECRET <your-clientSecret>

setx AZURE_TENANT_ID <your-tenantId>

setx KEY_VAULT_NAME <your-key-vault-name>

Each time you call setx, you should get a response of "SUCCESS: Specified value was saved."

Object model

The Azure Key Vault client library for .NET allows you to manage keys and related assets such as certificates and secrets. The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

The entire console app is available at https://github.com/Azure-Samples/key-vault-dotnet-core-quickstart/tree/master/key-vault-console-app.

Code examples

Add directives

Add the following directives to the top of your code:

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

Authenticate and create a client

Authenticating to your key vault and creating a key vault client depends on the environmental variables in the Set environmental variables step above. The name of your key vault is expanded to the key vault URI, in the format "https://.vault.azure.net".

string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.net";

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

Save a secret

Now that your application is authenticated, you can put a secret into your keyvault using the client.SetSecret method This requires a name for the secret -- we're using "mySecret" in this sample.

client.SetSecret(secretName, secretValue);

You can verify that the secret has been set with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret

Retrieve a secret

You can now retrieve the previously set value with the client.GetSecret method.

KeyVaultSecret secret = client.GetSecret(secretName);

Your secret is now saved as secret.Value.

Delete a secret

Finally, let's delete the secret from your key vault with the client.DeleteSecret method.

client.StartDeleteSecret(secretName);

You can verify that the secret is gone with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret

Clean up resources

When no longer needed, you can use the Azure CLI or Azure PowerShell to remove your key vault and the corresponding resource group.

az group delete -g "myResourceGroup" -l "EastUS" 
Remove-AzResourceGroup -Name "myResourceGroup"

Sample code

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

namespace key_vault_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
            string secretName = "mySecret";

            string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
            var kvUri = "https://" + keyVaultName + ".vault.azure.net";

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

            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.");

        }
    }
}

Next steps

In this quickstart you created a key vault, stored a secret, and retrieved that secret. See the entire console app in GitHub.

To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.