Skip to content

Latest commit

 

History

History
310 lines (252 loc) · 15.6 KB

File metadata and controls

310 lines (252 loc) · 15.6 KB

Azure Key Vault Secret client library for Java

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 tightly 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.

Use the secret client library to create and manage secrets.

Source code | API reference documentation | Product documentation | Samples

Getting started

Adding the package to your project

Maven dependency for Azure Secret Client library. Add it to your project's pom file.

<dependency>
    <groupId>com.azure.security</groupId>
    <artifactId>azure-keyvault-secrets</artifactId>
    <version>1.0.0-preview.1</version>
</dependency>

Prerequisites

  • Java Development Kit (JDK) with version 8 or above

  • Azure Subscription

  • An existing Azure Key Vault. If you need to create a Key Vault, you can use the Azure Cloud Shell to create one with this Azure CLI command. 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 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.

The DefaultAzureCredential way of authentication by providing client secret credentials is being used in this getting started section but you can find more ways to authenticate with azure-identity.

Create/Get credentials

To create/get client secret credentials you can use the Azure Portal, Azure CLI or Azure Cloud Shell

Here is Azure Cloud Shell snippet below to

  • Create a service principal and configure its access to Azure resources:

    az ad sp create-for-rbac -n <your-application-name> --skip-assignment

    Output:

    {
        "appId": "generated-app-ID",
        "displayName": "dummy-app-name",
        "name": "http://dummy-app-name",
        "password": "random-password",
        "tenant": "tenant-ID"
    }
  • Use the above returned credentials information 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 Bash:

      export AZURE_CLIENT_ID="generated-app-ID"
      export AZURE_CLIENT_SECRET="random-password"
      export AZURE_TENANT_ID="tenant-ID"
  • Grant the above mentioned application authorization to perform secret operations on the keyvault:

    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 retreive details of your Vault which also contains your Key Vault URL:

    az keyvault show --name <your-key-vault-name> 

Create Secret client

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:

import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.secrets.SecretClient;

SecretClient client = SecretClient.builder()
        .endpoint(<your-vault-url>)
        .credential(new DefaultAzureCredential())
        .build();

NOTE: For using Asynchronous client use SecretAsyncClient instead of SecretClient

Key concepts

Secret

A secret is the fundamental resource within Azure KeyVault. From a developer's perspective, Key Vault APIs accept and return secret values as strings. In addition to the secret data, the following attributes may be specified:

  • expires: Identifies the expiration time on or after which the secret data should not be retrieved.
  • notBefore: Identifies the time after which the secret will be active.
  • enabled: Specifies whether the secret data can be retrieved.
  • created: Indicates when this version of the secret was created.
  • updated: Indicates when this version of the secret was updated.

Secret Client:

The Secret client performs the interactions with the Azure Key Vault service for getting, setting, updating, deleting, and listing secrets and its versions. An asynchronous and synchronous, SecretClient, client 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.

Examples

Sync API

The following sections provide several code snippets covering some of the most common Azure Key Vault Secret Service tasks, including:

Create a Secret

Create a Secret to be stored in the Azure Key Vault.

  • setSecret creates a new secret in the key vault. if the secret with name already exists then a new version of the secret is created.
import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.models.Secret;

SecretClient secretClient = SecretClient.builder()
        .endpoint(<your-vault-url>)
        .credential(new DefaultAzureCredential())
        .build();

Secret secret = secretClient.setSecret("secret_name", "secret_value").value();
System.out.printf("Secret is created with name %s and value %s \n", secret.name(), secret.value());

Retrieve a Secret

Retrieve a previously stored Secret by calling getSecret.

Secret secret = secretClient.getSecret("secret_name").value();
System.out.printf("Secret is returned with name %s and value %s \n", secret.name(), secret.value());

Update an existing Secret

Update an existing Secret by calling updateSecret.

// Get the secret to update.
Secret secret = secretClient.getSecret("secret_name").value();
// Update the expiry time of the secret.
secret.expires(OffsetDateTime.now().plusDays(30));
SecretBase updatedSecret = secretClient.updateSecret(secret).value();
System.out.printf("Secret's updated expiry time %s \n", updatedSecret.expires().toString());

Delete a Secret

Delete an existing Secret by calling deleteSecret.

DeletedSecret deletedSecret = client.deleteSecret("secret_name").value();
System.out.printf("Deleted Secret's deletion date %s", deletedSecret.deletedDate().toString());

List Secrets

List the secrets in the key vault by calling listSecrets.

// List operations don't return the secrets with value information. So, for each returned secret we call getSecret to get the secret with its value information.
for (SecretBase secret : client.listSecrets()) {
    Secret secretWithValue  = client.getSecret(secret).value();
    System.out.printf("Received secret with name %s and value %s \n", secretWithValue.name(), secretWithValue.value());
}

Async API

The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Secret Service tasks, including:

Create a Secret Asynchronously

Create a Secret to be stored in the Azure Key Vault.

  • setSecret creates a new secret in the key vault. if the secret with name already exists then a new version of the secret is created.
import com.azure.identity.credential.DefaultAzureCredential;
import com.azure.security.keyvault.secrets.SecretAsyncClient;
import com.azure.security.keyvault.secrets.models.Secret;

SecretAsyncClient secretAsyncClient = SecretAsyncClient.builder()
        .endpoint(<your-vault-url>)
        .credential(new DefaultAzureCredential())
        .build();

secretAsyncClient.setSecret("secret_name", "secret_value").subscribe(secretResponse ->
  System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Retrieve a Secret Asynchronously

Retrieve a previously stored Secret by calling getSecret.

secretAsyncClient.getSecret("secretName").subscribe(secretResponse ->
  System.out.printf("Secret with name %s , value %s \n", secretResponse.value().name(),
  secretResponse.value().value()));

Update an existing Secret Asynchronously

Update an existing Secret by calling updateSecret.

secretAsyncClient.getSecret("secretName").subscribe(secretResponse -> {
     // Get the Secret
     Secret secret = secretResponse.value();
     // Update the expiry time of the secret.
     secret.expires(OffsetDateTime.now().plusDays(50));
     secretAsyncClient.updateSecret(secret).subscribe(secretResponse ->
         System.out.printf("Secret's updated not before time %s \n", secretResponse.value().notBefore().toString()));
   });

Delete a Secret Asynchronously

Delete an existing Secret by calling deleteSecret.

secretAsyncClient.deleteSecret("secretName").subscribe(deletedSecretResponse ->
   System.out.printf("Deleted Secret's deletion time %s \n", deletedSecretResponse.value().deletedDate().toString()));

List Secrets Asynchronously

List the secrets in the key vault by calling listSecrets.

// The List Secrets operation returns secrets without their value, so for each secret returned we call `getSecret` to get its // value as well.
secretAsyncClient.listSecrets()
  .flatMap(secretAsyncClient::getSecret).subscribe(secretResponse ->
    System.out.printf("Secret with name %s , value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Troubleshooting

General

Key Vault clients raise exceptions. For example, if you try to retrieve a secret after it is deleted a 404 error is returned, indicating resource not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

try {
    SecretClient.getSecret("deletedSecret")
} catch (ResourceNotFoundException e) {
    System.out.println(e.getMessage());
}

Next steps

Several KeyVault Java SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Key Vault:

Hello World Samples

List Operations Samples

Backup And Restore Operations Samples

Managing Deleted Secrets Samples:

Additional Documentation

For more extensive documentation on Azure Key Vault, see the API reference documentation.

Contributing

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.