Azure Key Vault is a cloud service that provides a secure storage of secrets, such as passwords and database connection strings.
Secret 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
Install the Azure Key Vault client library for .NET with NuGet:
Install-Package Azure.Security.KeyVault.Secrets -IncludePrerelease
- An Azure subscription.
- An existing Key Vault. If you need to create a Key Vault, you can use the Azure Portal or Azure CLI.
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>
In order to interact with the Key Vault service, you'll need to create an instance of the SecretClient class. You would need a vault url and client secret credentials (client id, client secret, tenant id) to instantiate a client object.
Client secret credential authentication is being used in this getting started section but you can find more ways to authenticate with Azure identity.
Use the Azure CLI snippet below to create/get client secret credentials.
- Create a service principal and configure its access to Azure resources:
Output:
az ad sp create-for-rbac -n <your-application-name> --skip-assignment
{ "appId": "generated-app-ID", "displayName": "dummy-app-name", "name": "http://dummy-app-name", "password": "random-password", "tenant": "tenant-ID" }
- Use the returned credentials above to set AZURE_CLIENT_ID(appId), AZURE_CLIENT_SECRET(password) and AZURE_TENANT_ID(tenant) environment variables. The following example shows a way to do this in Powershell:
$Env:AZURE_CLIENT_ID="generated-app-ID"
$Env:AZURE_CLIENT_SECRET="random-password"
$Env:AZURE_TENANT_ID="tenant-ID"
-
Grant the above mentioned application authorization to perform secret operations on the key vault:
az keyvault set-policy --name <your-key-vault-name> --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list set
--secret-permissions: Accepted values: backup, delete, get, list, purge, recover, restore, set
-
Use the above mentioned Key Vault name to retrieve details of your Vault which also contains your Key Vault URL:
az keyvault show --name <your-key-vault-name>
Once you've populated the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID environment variables and replaced your-vault-url with the above returned URI, you can create the SecretClient:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
// Create a new secret client using the default credential from Azure.Identity
var client = new SecretClient(vaultUri: <your-vault-url>, credential: new DefaultAzureCredential());
// Create a new secret using the secret client
Secret secret = client.Set("secret-name", "secret-value");
new DefaultAzureCredential(): Uses the environment variables previously set (
AZURE_CLIENT_ID
,AZURE_CLIENT_SECRET
, andAZURE_TENANT_ID
)
A secret is the fundamental resource within Azure KeyVault. From a developer's perspective, Key Vault APIs accept and return secret values as strings.
A SecretClient providing both synchronous and asynchronous operations exists 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 the primary resource types in Key Vault.
The Azure.Security.KeyVault.Secrets package supports synchronous and asynchronous APIs.
The following section provides several code snippets using the above created client
, covering some of the most common Azure Key Vault Secret service related tasks:
Set
creates a Secret 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.
Secret secret = client.Set("secret-name", "secret-value");
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);
Console.WriteLine(secret.Version);
Console.WriteLine(secret.Enabled);
Get
retrieves a secret previously stored in the Key Vault.
Secret secret = client.Get("secret-name");
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);
Update
updates a secret previously stored in the Key Vault.
Secret secret = new Secret("secret-name");
// Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved
secret.ContentType = "text/plain";
// You can specify additional application-specific metadata in the form of tags.
secret.Tags["foo"] = "updated tag";
SecretBase updatedSecret = client.Update(secret);
Console.WriteLine(updatedSecret.Name);
Console.WriteLine(updatedSecret.Value);
Console.WriteLine(updatedSecret.Version);
Console.WriteLine(updatedSecret.ContentType);
Delete
deletes a secret previously stored in the Key Vault. When soft-delete is not enabled for the Key Vault, this operation permanently deletes the secret.
DeletedSecret secret = client.Delete("secret-name");
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);
This example lists all the secrets in the specified Key Vault.
IEnumerable<Response<SecretBase>> allSecrets = client.GetSecrets();
foreach (Secret secret in allSecrets)
{
Console.WriteLine(secret.Name);
}
Async APIs are identical to their synchronous counterparts. Note that all methods end with Async
.
This example creates a secret in the Key Vault with the specified optional arguments.
Secret secret = await client.SetAsync("secret-name", "secret-value");
Console.WriteLine(secret.Name);
Console.WriteLine(secret.Value);
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 Key Vault, a 404
error is returned, indicating Not Found
.
try
{
Secret secret = client.Get("some_secret");
}
catch (RequestFailedException ex)
{
System.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
Several 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 Key Vault:
-
HelloWorld.cs and HelloWorldAsync.cs - for working with Azure Key Vault, including:
- Create a secret
- Get an existing secret
- Update an existing secret
- Delete secret
-
BackupAndRestore.cs and BackupAndRestoreAsync.cs - Contains the code snippets working with Key Vault secrets, including:
- Backup and recover a secret
-
GetSecrets.cs and GetSecretsAsync.cs - Example code for working with 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
- For more extensive documentation on Azure Key Vault, see the API reference documentation.
- For Keys client library see Keys client library.
- For Certificates client library see Certificates client library.
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.