Azure.Security.KeyVault.Secrets 4.7.0

Azure Key Vault secret client library for .NET

Azure Key Vault is a cloud service that provides a secure storage of secrets, such as passwords and database connection strings.

The Azure Key Vault secrets client library allows you to securely store and control the access to tokens, passwords, API keys, and other secrets. This library offers operations to create, retrieve, update, delete, purge, backup, restore, and list the secrets and its versions.

Source code | Package (NuGet) | API reference documentation | Product documentation | Samples | Migration guide

Getting started

Install the package

Install the Azure Key Vault secrets client library for .NET with NuGet:

dotnet add package Azure.Security.KeyVault.Secrets

Prerequisites

  • An Azure subscription.
  • An existing Azure Key Vault. If you need to create an Azure Key Vault, you can use the Azure Portal or Azure CLI.
  • Authorization to an existing Azure Key Vault using either RBAC (recommended) or access control.

If you use the Azure CLI, replace <your-resource-group-name> and <your-key-vault-name> with your own, unique names:

az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>

Authenticate the client

In order to interact with the Azure Key Vault service, you'll need to create an instance of the SecretClient class. You need a vault url, which you may see as "DNS Name" in the portal, and credentials to instantiate a client object.

The examples shown below use a DefaultAzureCredential, which is appropriate for most scenarios including local development and production environments. Additionally, we recommend using a managed identity for authentication in production environments. You can find more information on different ways of authenticating and their corresponding credential types in the Azure Identity documentation.

To use the DefaultAzureCredential provider shown below, or other credential providers provided with the Azure SDK, you must first install the Azure.Identity package:

dotnet add package Azure.Identity

Instantiate a DefaultAzureCredential to pass to the client. The same instance of a token credential can be used with multiple clients if they will be authenticating with the same identity.

// Create a new secret client using the default credential from Azure.Identity using environment variables previously set,
// including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
var client = new SecretClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

// Create a new secret using the secret client.
KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value");

// Retrieve a secret using the secret client.
secret = client.GetSecret("secret-name");

Key concepts

KeyVaultSecret

A KeyVaultSecret is the fundamental resource within Azure Key Vault. From a developer's perspective, Azure Key Vault APIs accept and return secret values as strings.

SecretClient

A SecretClient provides both synchronous and asynchronous operations in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a SecretClient, you can interact with secrets in Azure Key Vault.

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

Examples

The Azure.Security.KeyVault.Secrets package supports synchronous and asynchronous APIs.

The following section provides several code snippets using the client created above, covering some of the most common Azure Key Vault secret service related tasks:

Sync examples

Async examples

Create a secret

SetSecret creates a KeyVaultSecret to be stored in the Azure Key Vault. If a secret with the same name already exists, then a new version of the secret is created.

KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value");

Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);
Console.WriteLine(secret.Properties.Version);
Console.WriteLine(secret.Properties.Enabled);

Retrieve a secret

GetSecret retrieves a secret previously stored in the Azure Key Vault.

KeyVaultSecret secret = client.GetSecret("secret-name");

Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);

Update an existing secret

UpdateSecretProperties updates a secret previously stored in the Azure Key Vault. Only the attributes of the secret are updated. To update the value, call SecretClient.SetSecret on a secret with the same name.

KeyVaultSecret secret = client.GetSecret("secret-name");

// Clients may specify the content type of a secret to assist in interpreting the secret data when its retrieved.
secret.Properties.ContentType = "text/plain";

// You can specify additional application-specific metadata in the form of tags.
secret.Properties.Tags["foo"] = "updated tag";

SecretProperties updatedSecretProperties = client.UpdateSecretProperties(secret.Properties);

Console.WriteLine(updatedSecretProperties.Name);
Console.WriteLine(updatedSecretProperties.Version);
Console.WriteLine(updatedSecretProperties.ContentType);

Delete a secret

StartDeleteSecret starts a long-running operation to delete a secret previously stored in the Azure Key Vault. You can retrieve the secret immediately without waiting for the operation to complete. When soft-delete is not enabled for the Azure Key Vault, this operation permanently deletes the secret.

DeleteSecretOperation operation = client.StartDeleteSecret("secret-name");

DeletedSecret secret = operation.Value;
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);

Delete and purge a secret

You will need to wait for the long-running operation to complete before trying to purge or recover the secret. You can do this by calling UpdateStatus in a loop as shown below:

DeleteSecretOperation operation = client.StartDeleteSecret("secret-name");

// You only need to wait for completion if you want to purge or recover the secret.
// You should call `UpdateStatus` in another thread or after doing additional work like pumping messages.
while (!operation.HasCompleted)
{
    Thread.Sleep(2000);

    operation.UpdateStatus();
}

DeletedSecret secret = operation.Value;
client.PurgeDeletedSecret(secret.Name);

List secrets

This example lists all the secrets in the specified Azure Key Vault. The value is not returned when listing all secrets. You will need to call SecretClient.GetSecret to retrieve the value.

Pageable<SecretProperties> allSecrets = client.GetPropertiesOfSecrets();

foreach (SecretProperties secretProperties in allSecrets)
{
    Console.WriteLine(secretProperties.Name);
}

Create a secret asynchronously

The asynchronous APIs are identical to their synchronous counterparts, but return with the typical "Async" suffix for asynchronous methods and return a Task.

This example creates a secret in the Azure Key Vault with the specified optional arguments.

KeyVaultSecret secret = await client.SetSecretAsync("secret-name", "secret-value");

Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);

List secrets asynchronously

Listing secrets does not rely on awaiting the GetPropertiesOfSecretsAsync method, but returns an AsyncPageable<SecretProperties> that you can use with the await foreach statement:

AsyncPageable<SecretProperties> allSecrets = client.GetPropertiesOfSecretsAsync();

await foreach (SecretProperties secretProperties in allSecrets)
{
    Console.WriteLine(secretProperties.Name);
}

Delete a secret asynchronously

When deleting a secret asynchronously before you purge it, you can await the WaitForCompletionAsync method on the operation. By default, this loops indefinitely but you can cancel it by passing a CancellationToken.

DeleteSecretOperation operation = await client.StartDeleteSecretAsync("secret-name");

// You only need to wait for completion if you want to purge or recover the secret.
await operation.WaitForCompletionAsync();

DeletedSecret secret = operation.Value;
await client.PurgeDeletedSecretAsync(secret.Name);

Troubleshooting

See our troubleshooting guide for details on how to diagnose various failure scenarios.

General

When you interact with the Azure Key Vault secret client library using the .NET SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests.

For example, if you try to retrieve a secret that doesn't exist in your Azure Key Vault, a 404 error is returned, indicating Not Found.

try
{
    KeyVaultSecret secret = client.GetSecret("some_secret");
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.ToString());
}

You will notice that additional information is logged, like the Client Request ID of the operation.

Message:
    Azure.RequestFailedException : Service request failed.
    Status: 404 (Not Found)
Content:
    {"error":{"code":"SecretNotFound","message":"Secret not found: some_secret"}}

Headers:
    Cache-Control: no-cache
    Pragma: no-cache
    Server: Microsoft-IIS/10.0
    x-ms-keyvault-region: westus
    x-ms-request-id: 625f870e-10ea-41e5-8380-282e5cf768f2
    x-ms-keyvault-service-version: 1.1.0.866
    x-ms-keyvault-network-info: addr=131.107.174.199;act_addr_fam=InterNetwork;
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Strict-Transport-Security: max-age=31536000;includeSubDomains
    X-Content-Type-Options: nosniff
    Date: Tue, 18 Jun 2019 16:02:11 GMT
    Content-Length: 75
    Content-Type: application/json; charset=utf-8
    Expires: -1

Next steps

Several Azure Key Vault secrets client library samples are available to you in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure Key Vault:

  • Sample1_HelloWorld.md - for working with Azure Key Vault, including:

    • Create a secret
    • Get an existing secret
    • Update an existing secret
    • Delete secret
  • Sample2_BackupAndRestore.md - contains the code snippets working with Azure Key Vault secrets, including:

    • Backup and recover a secret
  • Sample3_GetSecrets.md - example code for working with Azure Key Vault secrets, including:

    • Create secrets
    • List all secrets in the Key Vault
    • Update secrets in the Key Vault
    • List versions of a specified secret
    • Delete secrets from the Key Vault
    • List deleted secrets in the Key Vault

Additional Documentation

Contributing

See the CONTRIBUTING.md for details on building, testing, and contributing to these libraries.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Showing the top 20 packages that depend on Azure.Security.KeyVault.Secrets.

Packages Downloads
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'cda28e5941e47b2b2a3d9bea20f78d11af1d92e0' (see contained AppVeyorSettings.json file for build settings).
15
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '011956b31c05f14f3233f6241cd6fbe038824d71' (see contained AppVeyorSettings.json file for build settings).
7
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'bbceff250ec4c9c604b33b38600ab9b4a4e17dac' (see contained AppVeyorSettings.json file for build settings).
6
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'aeacff85068cb9218354491b39fbf916e5ea28e8' (see contained AppVeyorSettings.json file for build settings).
6
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '369ef2b8fd696c639b333812edf5c5fdd5f3e7e6' (see contained AppVeyorSettings.json file for build settings).
4
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '1688d821b6cef6e19f869ca665d7b0ba4c33255a' (see contained AppVeyorSettings.json file for build settings).
3
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'ea86450b4db1568563b15122f0250495fd55776e' (see contained AppVeyorSettings.json file for build settings).
3
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'f6123b1450735fa0fc6dd2713b40f23019f470b1' (see contained AppVeyorSettings.json file for build settings).
2
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'e782a00085e84e022c341a265b54c0c9308cbe78' (see contained AppVeyorSettings.json file for build settings).
2
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'a94fbe2ca0c12a4bf2df0a4c92e9dc51ee8f1076' (see contained AppVeyorSettings.json file for build settings).
2
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'd8ff60a63e8e7bb77b64c9820c42add96835772d' (see contained AppVeyorSettings.json file for build settings).
2
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '9ced2aa3a6cecfbea5ef45d692ef7f156da0dbe0' (see contained AppVeyorSettings.json file for build settings).
2
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '245ccadae9fc856bef1b7c929958e3230fd1f729' (see contained AppVeyorSettings.json file for build settings).
1
Nuke.Common
The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit '45063fd8e8531a3146ee64c9d93f1d3360062c29' (see contained AppVeyorSettings.json file for build settings).
1

https://github.com/Azure/azure-sdk-for-net/blob/Azure.Security.KeyVault.Secrets_4.7.0/sdk/keyvault/Azure.Security.KeyVault.Secrets/CHANGELOG.md

.NET Standard 2.0

Version Downloads Last updated
4.7.0 4 10/20/2024
4.6.0 18 02/19/2024
4.6.0-beta.2 4 02/20/2024
4.6.0-beta.1 4 12/21/2023
4.5.0 8 08/31/2023
4.5.0-beta.1 4 06/13/2023
4.4.0 9 08/26/2023
4.3.0 6 08/26/2023
4.3.0-beta.4 6 06/12/2023
4.3.0-beta.2 5 01/28/2024
4.3.0-beta.1 5 06/12/2023
4.2.0 6 08/29/2023
4.2.0-beta.5 7 06/14/2023
4.2.0-beta.4 4 06/12/2023
4.2.0-beta.3 4 06/14/2023
4.2.0-beta.2 4 06/13/2023
4.2.0-beta.1 5 06/13/2023
4.1.0 7 08/29/2023
4.1.0-preview.1 10 06/13/2023
4.0.3 4 02/19/2024
4.0.2 5 01/15/2024
4.0.1 6 08/25/2023
4.0.0 7 08/27/2023
4.0.0-preview.5 6 06/13/2023
4.0.0-preview.4 4 02/20/2024
4.0.0-preview.3 5 06/13/2023
4.0.0-preview.2 4 02/19/2024
4.0.0-preview.1 5 06/13/2023