Quickstart: Azure Key Vault client library for .NET

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 akvdotnet

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 Microsoft.Azure.KeyVault

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

dotnet add package System.Threading.Tasks
dotnet add package Microsoft.IdentityModel.Clients.ActiveDirectory
dotnet add package Microsoft.Azure.Management.ResourceManager.Fluent

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 and clientSecret, as we will use them in the Authenticate to your key vault step below.

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

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 set a secret and retrieve a secret.

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

Code examples

Add directives

Add the following directives to the top of your code:

using System;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;

Authenticate to your key vault

This .NET quickstart relies on environment variables to store credentials that should not be put in code.

Before you build and run your app, use the setx command to set the akvClientId, akvClientSecret, akvTenantId, and akvSubscriptionId environment variables to the values you noted above.

setx akvClientId <your-clientID>

setx akvClientSecret <your-clientSecret>

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

Assign these environment variables to strings in your code, and then authenticate your application by passing them to the KeyVaultClient class:


string clientId = Environment.GetEnvironmentVariable("akvClientId");
string clientSecret = Environment.GetEnvironmentVariable("akvClientSecret");

KeyVaultClient kvClient = new KeyVaultClient(async (authority, resource, scope) =>
{
    var adCredential = new ClientCredential(clientId, clientSecret);
    var authenticationContext = new AuthenticationContext(authority, null);
    return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
});

Save a secret

Now that your application is authenticated, you can put a secret into your keyvault using the SetSecretAsync method This requires the URL of your key vault, which is in the form https://<your-unique-keyvault-name>.vault.azure.net/secrets/. It also requires a name for the secret -- we're using "mySecret". You may wish to assign these strings to a variables for reuse.

await kvClient.SetSecretAsync($"{kvURL}", 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 GetSecretAsync method

var keyvaultSecret = await kvClient.GetSecretAsync($"{kvURL}", secretName).ConfigureAwait(false);

Your secret is now saved as keyvaultSecret.Value;.

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"

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.