Quickstart: Azure Key Vault secret client library for .NET
Get started with the Azure Key Vault secret client library for .NET. Azure Key Vault is a cloud service that provides a secure store for secrets. You can securely store keys, passwords, certificates, and other secrets. Azure key vaults may be created and managed through the Azure portal. In this quickstart, you learn how to create, retrieve, and delete secrets from an Azure key vault using the .NET client library
Key Vault client library resources:
API reference documentation | Library source code | Package (NuGet)
For more information about Key Vault and secrets, see:
Prerequisites
- An Azure subscription - Create a trial subscription
- .NET 6 SDK or later
- Azure CLI or Azure PowerShell
- A Key Vault - you can create one using Azure portal, Azure CLI, or Azure PowerShell
This quickstart is using dotnet
and Azure CLI or Azure PowerShell.
Setup
This quickstart is using Azure Identity library with Azure CLI to authenticate user to Azure Services. Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.
Sign in to Azure
Run the
az login
command.az cloud set -n AzureChinaCloud az login # az cloud set -n AzureCloud //means return to Public Azure.
If the CLI can open your default browser, it will do so and load an Azure sign-in page.
Otherwise, open a browser page at https://aka.ms/deviceloginchina and enter the authorization code displayed in your terminal.
Sign in with your account credentials in the browser.
Grant access to your key vault
To grant your application permissions to your key vault through Role-Based Access Control (RBAC), assign a role using the Azure CLI command az role assignment create.
az role assignment create --role "Key Vault Secrets User" --assignee "<app-id>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"
Replace <app-id>
, <subscription-id>
, <resource-group-name>
and <your-unique-keyvault-name>
with your actual values. <app-id>
is the Application (client) ID of your registered application in Azure Entra.
Create new .NET console app
In a command shell, run the following command to create a project named
key-vault-console-app
:dotnet new console --name key-vault-console-app
Change to the newly created key-vault-console-app directory, and run the following command to build the project:
dotnet build
The build output should contain no warnings or errors.
Build succeeded. 0 Warning(s) 0 Error(s)
Install the packages
From the command shell, install the Azure Key Vault secret client library for .NET:
dotnet add package Azure.Security.KeyVault.Secrets
For this quickstart, you'll also need to install the Azure Identity client library:
dotnet add package Azure.Identity
Set environment variables
This application is using key vault name as an environment variable called KEY_VAULT_NAME
.
Windows
set KEY_VAULT_NAME=<your-key-vault-name>
Windows PowerShell
$Env:KEY_VAULT_NAME="<your-key-vault-name>"
macOS or Linux
export KEY_VAULT_NAME=<your-key-vault-name>
Object model
The Azure Key Vault secret client library for .NET allows you to manage secrets. The Code examples section shows how to create a client, set a secret, retrieve a secret, and delete a secret.
Code examples
Add directives
Add the following directives to the top of Program.cs:
// <directives>
using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
// </directives>
namespace key_vault_console_app
{
class Program
{
static void Main(string[] args)
{
bool isSoftDeleteEnabled = true;
string secretName = "mySecret";
// <authenticate>
string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.cn";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
// </authenticate>
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 + "` ...");
// <setsecret>
client.SetSecret(secretName, secretValue);
// </setsecret>
Console.WriteLine(" done.");
Console.WriteLine("Forgetting your secret.");
secretValue = "";
Console.WriteLine("Your secret is '" + secretValue + "'.");
Console.WriteLine("Retrieving your secret from " + keyVaultName + ".");
// <getsecret>
KeyVaultSecret secret = client.GetSecret(secretName);
// </getsecret>
Console.WriteLine("Your secret is '" + secret.Value + "'.");
Console.Write("Deleting your secret from " + keyVaultName + " ...");
// <deletesecret>
client.StartDeleteSecret(secretName);
// </deletesecret>
if (!isSoftDeleteEnabled)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine(" done.");
return;
}
System.Threading.Thread.Sleep(60000);
Console.WriteLine(" done.");
Console.Write("Purging your secret from " + keyVaultName + " ...");
// <purgesecret>
client.PurgeDeletedSecret(secretName);
// </purgesecret>
System.Threading.Thread.Sleep(5000);
Console.WriteLine(" done.");
}
}
}
Authenticate and create a client
Application requests to most Azure services must be authorized. Using the DefaultAzureCredential class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code. DefaultAzureCredential
supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.
In this quickstart, DefaultAzureCredential
authenticates to key vault using the credentials of the local development user logged into the Azure CLI. When the application is deployed to Azure, the same DefaultAzureCredential
code can automatically discover and use a managed identity that is assigned to an App Service, Virtual Machine, or other services. For more information, see Managed Identity Overview.
In this example, the name of your key vault is expanded to the key vault URI, in the format https://<your-key-vault-name>.vault.azure.cn
. For more information about authenticating to key vault, see Developer's Guide.
// <directives>
using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
// </directives>
namespace key_vault_console_app
{
class Program
{
static void Main(string[] args)
{
bool isSoftDeleteEnabled = true;
string secretName = "mySecret";
// <authenticate>
string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.cn";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
// </authenticate>
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 + "` ...");
// <setsecret>
client.SetSecret(secretName, secretValue);
// </setsecret>
Console.WriteLine(" done.");
Console.WriteLine("Forgetting your secret.");
secretValue = "";
Console.WriteLine("Your secret is '" + secretValue + "'.");
Console.WriteLine("Retrieving your secret from " + keyVaultName + ".");
// <getsecret>
KeyVaultSecret secret = client.GetSecret(secretName);
// </getsecret>
Console.WriteLine("Your secret is '" + secret.Value + "'.");
Console.Write("Deleting your secret from " + keyVaultName + " ...");
// <deletesecret>
client.StartDeleteSecret(secretName);
// </deletesecret>
if (!isSoftDeleteEnabled)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine(" done.");
return;
}
System.Threading.Thread.Sleep(60000);
Console.WriteLine(" done.");
Console.Write("Purging your secret from " + keyVaultName + " ...");
// <purgesecret>
client.PurgeDeletedSecret(secretName);
// </purgesecret>
System.Threading.Thread.Sleep(5000);
Console.WriteLine(" done.");
}
}
}
Save a secret
Now that the console app is authenticated, add a secret to the key vault. For this task, use the SetSecretAsync method.
The method's first parameter accepts a name for the secret. In this sample, the variable secretName
stores the string "mySecret".
The method's second parameter accepts a value for the secret. In this sample, the secret is input by the user via the commandline and stored in the variable secretValue
.
await client.SetSecretAsync(secretName, secretValue);
Note
If secret name exists, the code will create new version of that secret.
Retrieve a secret
You can now retrieve the previously set value with the GetSecretAsync method.
var secret = await client.GetSecretAsync(secretName);
Your secret is now saved as secret.Value
.
Delete a secret
Finally, let's delete the secret from your key vault with the StartDeleteSecretAsync and PurgeDeletedSecretAsync methods.
var operation = await client.StartDeleteSecretAsync(secretName);
// You only need to wait for completion if you want to purge or recover the key.
await operation.WaitForCompletionAsync();
await client.PurgeDeletedSecretAsync(secretName);
Sample code
Modify the .NET console app to interact with the Key Vault by completing the following steps:
Replace the code in Program.cs with the following code:
using System; using System.Threading.Tasks; using Azure.Identity; using Azure.Security.KeyVault.Secrets; namespace key_vault_console_app { class Program { static async Task Main(string[] args) { const string secretName = "mySecret"; var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME"); var kvUri = $"https://{keyVaultName}.vault.azure.cn"; var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential()); Console.Write("Input the value of your secret > "); var secretValue = Console.ReadLine(); Console.Write($"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ..."); await client.SetSecretAsync(secretName, secretValue); Console.WriteLine(" done."); Console.WriteLine("Forgetting your secret."); secretValue = string.Empty; Console.WriteLine($"Your secret is '{secretValue}'."); Console.WriteLine($"Retrieving your secret from {keyVaultName}."); var secret = await client.GetSecretAsync(secretName); Console.WriteLine($"Your secret is '{secret.Value.Value}'."); Console.Write($"Deleting your secret from {keyVaultName} ..."); DeleteSecretOperation operation = await client.StartDeleteSecretAsync(secretName); // You only need to wait for completion if you want to purge or recover the secret. await operation.WaitForCompletionAsync(); Console.WriteLine(" done."); Console.Write($"Purging your secret from {keyVaultName} ..."); await client.PurgeDeletedSecretAsync(secretName); Console.WriteLine(" done."); } } }
Test and verify
Execute the following command to run the app.
dotnet run
When prompted, enter a secret value. For example, mySecretPassword.
A variation of the following output appears:
Input the value of your secret > mySecretPassword
Creating a secret in <your-unique-keyvault-name> called 'mySecret' with the value 'mySecretPassword' ... done.
Forgetting your secret.
Your secret is ''.
Retrieving your secret from <your-unique-keyvault-name>.
Your secret is 'mySecretPassword'.
Deleting your secret from <your-unique-keyvault-name> ... done.
Purging your secret from <your-unique-keyvault-name> ... done.
Next steps
To learn more about Key Vault and how to integrate it with your apps, see the following articles: