All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.azure.security.keyvault.secrets.SecretClient Maven / Gradle / Ivy

The newest version!
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.security.keyvault.secrets;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollingContext;
import com.azure.core.util.polling.SyncPoller;
import com.azure.security.keyvault.secrets.implementation.SecretClientImpl;
import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult;
import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle;
import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException;
import com.azure.security.keyvault.secrets.implementation.models.SecretBundle;
import com.azure.security.keyvault.secrets.models.DeletedSecret;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;
import com.azure.security.keyvault.secrets.models.SecretProperties;

import java.time.Duration;
import java.util.function.Function;
import java.util.function.Supplier;

import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapDeletedSecretItemPage;
import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapSecretItemPage;
import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createDeletedSecret;
import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createKeyVaultSecret;
import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretAttributes;
import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretProperties;

/**
 * The SecretClient provides synchronous methods to manage {@link KeyVaultSecret secrets} in the Azure Key Vault. The
 * client supports creating, retrieving, updating, deleting, purging, backing up, restoring, and listing the
 * {@link KeyVaultSecret secrets}. The client also supports listing {@link DeletedSecret deleted secrets} for a
 * soft-delete enabled key vault.
 *
 * 

Getting Started

* *

In order to interact with the Azure Key Vault service, you will need to create an instance of the * {@link SecretClient} class, a vault url and a credential object.

* *

The examples shown in this document use a credential object named DefaultAzureCredential for authentication, * 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".

* *

Sample: Construct Synchronous Secret client

* *
 * SecretClient secretClient = new SecretClientBuilder()
 *     .credential(new DefaultAzureCredentialBuilder().build())
 *     .vaultUrl("<your-key-vault-url>")
 *     .buildClient();
 * 
* * *
* *
* *

Create a Secret

* The {@link SecretClient} can be used to create a secret in the key vault. * *

Code Sample:

*

The following code sample demonstrates how to synchronously create and store a secret in the key vault, * using the {@link SecretClient#setSecret(String, String)} API.

* * *
 * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
 * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
 * 
* * *

Note: For the asynchronous sample, refer to * {@link com.azure.security.keyvault.secrets.SecretAsyncClient}.

* *
* *
* *

Get a Secret

* The {@link SecretClient} can be used to retrieve a secret from the key vault. * *

Code Sample:

*

The following code sample demonstrates how to synchronously retrieve a previously stored secret from the Azure * KeyVault, using the {@link SecretClient#getSecret(String)} API.

* * *
 * KeyVaultSecret secret = secretClient.getSecret("secretName");
 * System.out.printf("Secret is returned with name %s and value %s%n",
 *     secret.getName(), secret.getValue());
 * 
* * *

Note: For the asynchronous sample, refer to {@link SecretAsyncClient}.

* *
* *
* *

Delete a Secret

* The {@link SecretClient} can be used to delete a secret from the key vault. * *

Code Sample:

*

The following code sample demonstrates how to delete a secret from the key vault, using * the {@link SecretClient#beginDeleteSecret(String)} API.

* * *
 * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
 *
 * // Deleted Secret is accessible as soon as polling begins.
 * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
 *
 * // Deletion date only works for a SoftDelete-enabled Key Vault.
 * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
 *     .getDeletedOn().toString());
 * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
 *     .getRecoveryId());
 *
 * // Secret is being deleted on server.
 * deleteSecretPoller.waitForCompletion();
 * 
* * *

Note: For the asynchronous sample, refer to {@link SecretAsyncClient}.

* * @see SecretClientBuilder * @see SyncPoller * @see PagedIterable */ @ServiceClient(builder = SecretClientBuilder.class, serviceInterfaces = SecretClientImpl.SecretClientService.class) public final class SecretClient { private static final ClientLogger LOGGER = new ClientLogger(SecretClient.class); private final SecretClientImpl implClient; private final String vaultUrl; /** * Gets the vault endpoint url to which service requests are sent to. * @return the vault endpoint url. */ public String getVaultUrl() { return vaultUrl; } /** * Creates a SecretClient to service requests * * @param implClient the implementation client. * @param vaultUrl the vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; this.vaultUrl = vaultUrl; } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * *

The {@link SecretProperties#getExpiresOn() expires}, {@link SecretProperties#getContentType() contentType}, * and {@link SecretProperties#getNotBefore() notBefore} values in {@code secret} are optional. * If not specified, {@link SecretProperties#isEnabled() enabled} is set to true by key vault.

* *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

* *
     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
     *     .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
     * KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret);
     * System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(),
     *     returnedSecret.getValue());
     * 
* * * @param secret The Secret object containing information about the secret and its properties. The properties * {@link KeyVaultSecret#getName() secret.name} and {@link KeyVaultSecret#getValue() secret.value} cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpResponseException if {@link KeyVaultSecret#getName() name} or {@link KeyVaultSecret#getValue() value} * is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { return setSecretWithResponse(secret, Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

* *
     * KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue");
     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
     * 
* * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return The {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); } /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. * *

Code sample

*

Creates a new secret in the key vault. Prints out the details of the newly created secret returned in the * response.

* *
     * KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue")
     *     .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)));
     * KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue();
     * System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue());
     * 
* * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the * {@link KeyVaultSecret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} is specified. * @throws HttpResponseException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { SecretProperties secretProperties = secret.getProperties(); if (secretProperties == null) { Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), null, null, null, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } else { Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), secret.getValue(), secretProperties.getTags(), secretProperties.getContentType(), createSecretAttributes(secretProperties), context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); } }, SecretAsyncClient::mapSetSecretException); } /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. * *

Code sample

*

Gets the latest version of the secret in the key vault. Prints out the details of the returned secret.

* *
     * KeyVaultSecret secret = secretClient.getSecret("secretName");
     * System.out.printf("Secret is returned with name %s and value %s%n",
     *     secret.getName(), secret.getValue());
     * 
* * * @param name The name of the secret. * @return The requested {@link KeyVaultSecret}. * @throws ResourceNotFoundException When a secret with the given {@code name} doesn't exist in the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { return getSecretWithResponse(name, null, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * *

Code sample

*

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

* *
     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
     * KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion);
     * System.out.printf("Secret is returned with name %s and value %s%n",
     *     secretWithVersion.getName(), secretWithVersion.getValue());
     * 
* * * @param name The name of the secret, cannot be null. * @param version The version of the secret to retrieve. If this is an empty string or null, this call is * equivalent to calling {@link #getSecret(String)}, with the latest version being retrieved. * @return The requested {@link KeyVaultSecret secret}. * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. * @throws HttpResponseException If the server reports an error when executing the request. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { return getSecretWithResponse(name, version, Context.NONE).getValue(); } /** * Gets the specified secret with specified version from the key vault. This operation requires the * {@code secrets/get} permission. * *

Code sample

*

Gets a specific version of the secret in the key vault. Prints out the details of the returned secret.

* *
     * String secretVersion = "6A385B124DEF4096AF1361A85B16C204";
     * KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion,
     *     new Context(key2, value2)).getValue();
     * System.out.printf("Secret is returned with name %s and value %s%n",
     *     secretWithVersion.getName(), secretWithVersion.getValue());
     * 
* * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty string or null, this call is equivalent * to calling {@link #getSecret(String)}, with the latest version being retrieved. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the requested {@link KeyVaultSecret}. * @throws ResourceNotFoundException When a secret with the given {@code name} and {@code version} doesn't exist in * the vault. * @throws IllegalArgumentException If {@code name} is either {@code null} or empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getSecretWithResponse(String name, String version, Context context) { if (CoreUtils.isNullOrEmpty(name)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); } return callWithMappedException(() -> { Response response = implClient.getSecretWithResponse(vaultUrl, name, version, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapGetSecretException); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and * {@link SecretProperties#getVersion() version} cannot be null.

* *

Code sample

*

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key * vault.

* *
     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
     * SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties);
     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName());
     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
     * 
* * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @return The {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. * @throws HttpResponseException if {@link SecretProperties#getName() name} or * {@link SecretProperties#getVersion() version} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); } /** * Updates the attributes associated with the secret. The value of the secret in the key vault cannot be changed. * Only attributes populated in {@code secretProperties} are changed. Attributes not specified in the request are * not changed. This operation requires the {@code secrets/set} permission. * *

The {@code secret} is required and its fields {@link SecretProperties#getName() name} and * {@link SecretProperties#getVersion() version} cannot be null.

* *

Code sample

*

Gets the latest version of the secret, changes its expiry time, and the updates the secret in the key vault. *

* *
     * SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties();
     * secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60));
     * SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties,
     *     new Context(key2, value2)).getValue();
     * KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName());
     * System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n",
     *     updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn());
     * 
* * * @param secretProperties The {@link SecretProperties secret properties} object with updated properties. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the * {@link SecretProperties updated secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceNotFoundException when a secret with {@link SecretProperties#getName() name} and * {@link SecretProperties#getVersion() version} doesn't exist in the key vault. * @throws HttpResponseException if {@link SecretProperties#getName() name} or * {@link SecretProperties#getVersion() version} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { Response response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), secretProperties.getContentType(), createSecretAttributes(secretProperties), secretProperties.getTags(), context); return new SimpleResponse<>(response, createSecretProperties(response.getValue())); } /** * Deletes a secret from the key vault. If soft-delete is enabled on the key vault then the secret is placed in the * deleted state and for permanent deletion, needs to be purged. Otherwise, the secret is permanently deleted. * All versions of a secret are deleted. This cannot be applied to individual versions of a secret. * This operation requires the {@code secrets/delete} permission. * *

Code sample

*

Deletes the secret from a soft-delete enabled key vault. Prints out the recovery id of the deleted secret * returned in the response.

* *
     * SyncPoller<DeletedSecret, Void> deleteSecretPoller = secretClient.beginDeleteSecret("secretName");
     *
     * // Deleted Secret is accessible as soon as polling begins.
     * PollResponse<DeletedSecret> deleteSecretPollResponse = deleteSecretPoller.poll();
     *
     * // Deletion date only works for a SoftDelete-enabled Key Vault.
     * System.out.println("Deleted Date  %s" + deleteSecretPollResponse.getValue()
     *     .getDeletedOn().toString());
     * System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue()
     *     .getRecoveryId());
     *
     * // Secret is being deleted on server.
     * deleteSecretPoller.waitForCompletion();
     * 
* * * @param name The name of the secret to be deleted. * @return A {@link SyncPoller} to poll on and retrieve the {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller beginDeleteSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), deleteActivationOperation(name), deletePollOperation(name), (context, response) -> null, context -> null); } private Function, PollResponse> deleteActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), SecretAsyncClient::mapDeleteSecretException); } private Function, PollResponse> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { // This means either vault has soft-delete disabled or permission is not granted for the get deleted // key operation. In both cases deletion operation was successful when activation operation // succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { // This means either vault has soft-delete disabled or permission is not granted for the get deleted // key operation. In both cases deletion operation was successful when activation operation // succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * *

Code sample

*

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * deleted secret returned in the response.

* *
     * DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName");
     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
     * 
* * * @param name The name of the deleted secret. * @return The {@link DeletedSecret deleted secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { return getDeletedSecretWithResponse(name, Context.NONE).getValue(); } /** * Gets a secret that has been deleted for a soft-delete enabled key vault. This operation requires the * {@code secrets/list} permission. * *

Code sample

*

Gets the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * deleted secret returned in the response.

* *
     * DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName",
     *     new Context(key2, value2)).getValue();
     * System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId());
     * 
* * * @param name The name of the deleted secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the {@link DeletedSecret deleted * secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); }, SecretAsyncClient::mapGetDeletedSecretException); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a soft-delete enabled vault. This operation requires the {@code secrets/purge} permission. * *

Code sample

*

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from * the server response.

* * *
     * secretClient.purgeDeletedSecret("secretName");
     * 
* * * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { purgeDeletedSecretWithResponse(name, Context.NONE); } /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a soft-delete enabled vault. This operation requires the {@code secrets/purge} permission. * *

Code sample

*

Purges the deleted secret from the key vault enabled for soft-delete. Prints out the status code from * the server response.

* *
     * Response<Void> purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName",
     *     new Context(key1, value1));
     * System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode());
     * 
* * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response purgeDeletedSecretWithResponse(String name, Context context) { return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), SecretAsyncClient::mapPurgeDeletedSecretException); } /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a soft-delete * enabled vault. This operation requires the {@code secrets/recover} permission. * *

Code sample

*

Recovers the deleted secret from the key vault enabled for soft-delete. Prints out the details of the * recovered secret returned in the response.

* *
     * SyncPoller<KeyVaultSecret, Void> recoverSecretPoller =
     *     secretClient.beginRecoverDeletedSecret("deletedSecretName");
     *
     * // Deleted Secret can be accessed as soon as polling is in progress.
     * PollResponse<KeyVaultSecret> recoveredSecretPollResponse = recoverSecretPoller.poll();
     * System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName());
     * System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId());
     *
     * // Key is being recovered on server.
     * recoverSecretPoller.waitForCompletion();
     * 
* * * @param name The name of the deleted secret to be recovered. * @return A {@link SyncPoller} to poll on and retrieve the {@link KeyVaultSecret recovered secret}. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller beginRecoverDeletedSecret(String name) { return SyncPoller.createPoller(Duration.ofSeconds(1), recoverActivationOperation(name), recoverPollOperation(name), (context, response) -> null, context -> null); } private Function, PollResponse> recoverActivationOperation( String name) { return pollingContext -> callWithMappedException(() -> new PollResponse<>( LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), SecretAsyncClient::mapRecoverDeletedSecretException); } private Function, PollResponse> recoverPollOperation( String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); } catch (HttpResponseException ex) { if (ex.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { // This means permission is not granted for the get deleted key operation. In both cases the // deletion operation was successful when activation operation succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } } catch (Exception ex) { // This means permission is not granted for the get deleted key operation. In both cases the // deletion operation was successful when activation operation succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } }; } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * *

Code sample

*

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response

* *
     * byte[] secretBackup = secretClient.backupSecret("secretName");
     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
     * 
* * * @param name The name of the secret. * @return A {@link Response} whose {@link Response#getValue() value} contains the backed up secret blob. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { return backupSecretWithResponse(name, Context.NONE).getValue(); } /** * Requests a backup of the secret be downloaded to the client. All versions of the secret will be downloaded. * This operation requires the {@code secrets/backup} permission. * *

Code sample

*

Backs up the secret from the key vault and prints out the length of the secret's backup byte array returned in * the response

* * *
     * byte[] secretBackup = secretClient.backupSecretWithResponse("secretName",
     *     new Context(key1, value1)).getValue();
     * System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length);
     * 
* * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the backed up secret blob. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response backupSecretWithResponse(String name, Context context) { return callWithMappedException(() -> { Response response = implClient.backupSecretWithResponse(vaultUrl, name, context); return new SimpleResponse<>(response, response.getValue().getValue()); }, SecretAsyncClient::mapBackupSecretException); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * *

Code sample

*

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.

* * *
     * // Pass the secret backup byte array of the secret to be restored.
     * byte[] secretBackupByteArray = {};
     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray);
     * System.out
     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
     * 
* * * @param backup The backup blob associated with the secret. * @return A {@link Response} whose {@link Response#getValue() value} contains the * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); } /** * Restores a backed up secret, and all its versions, to a vault. * This operation requires the {@code secrets/restore} permission. * *

Code sample

*

Restores the secret in the key vault from its backup byte array. Prints out the details of the restored secret * returned in the response.

* * *
     * // Pass the secret backup byte array of the secret to be restored.
     * byte[] secretBackupByteArray = {};
     * KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray,
     *     new Context(key2, value2)).getValue();
     * System.out
     *     .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue());
     * 
* * * @param backup The backup blob associated with the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return A {@link Response} whose {@link Response#getValue() value} contains the * {@link KeyVaultSecret restored secret}. * @throws ResourceModifiedException when {@code backup} blob is malformed. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { Response response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); }, SecretAsyncClient::mapRestoreSecretException); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * *

Iterate through secrets and fetch their latest value

*

The snippet below loops over each {@link SecretProperties secret} and calls * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

* * *
     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) {
     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
     *     System.out.printf("Received secret with name %s and value %s",
     *         secretWithValue.getName(), secretWithValue.getValue());
     * }
     * 
* * *

Iterate over secrets by page

*

The snippet below loops over each {@link SecretProperties secret} by page and calls * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

* * *
     * secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> {
     *     System.out.printf("Response headers are %s. Url %s  and status code %d %n", resp.getHeaders(),
     *         resp.getRequest().getUrl(), resp.getStatusCode());
     *     resp.getItems().forEach(value -> {
     *         KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
     *         System.out.printf("Received secret with name %s and value %s",
     *             secretWithValue.getName(), secretWithValue.getValue());
     *     });
     * });
     * 
* * * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. The * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecrets() { return listPropertiesOfSecrets(Context.NONE); } /** * Lists secrets in the key vault. Each {@link SecretProperties secret} returned only has its identifier and * attributes populated. The secret values and their versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * *

Iterate over secrets and fetch their latest value

*

The snippet below loops over each {@link SecretProperties secret} and calls * {@link #getSecret(String, String) getSecret(String, String)}. This gets the {@link KeyVaultSecret secret} and the * value of its latest version.

* *
     * for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) {
     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
     *     System.out.printf("Received secret with name %s and value %s",
     *         secretWithValue.getName(), secretWithValue.getValue());
     * }
     * 
* * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the secrets in the vault. * {@link SecretProperties} contains all the information about the secret, except its value. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecrets(Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * *

Iterate over secrets

*

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

* *
     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) {
     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
     * }
     * 
* * *

Iterate over secrets by page

*

Iterate over Lists the deleted secrets by page in the key vault and for each deleted secret prints out its * recovery id.

* *
     * secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> {
     *     System.out.printf("Got response headers . Url: %s, Status code: %d %n",
     *         resp.getRequest().getUrl(), resp.getStatusCode());
     *     resp.getItems().forEach(value -> {
     *         System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId());
     *     });
     * });
     * 
* * * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedSecrets() { return listDeletedSecrets(Context.NONE); } /** * Lists {@link DeletedSecret deleted secrets} of the key vault if it has enabled soft-delete. This operation * requires the {@code secrets/list} permission. * *

Code sample

*

Lists the deleted secrets in the key vault and for each deleted secret prints out its recovery id.

* *
     * for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) {
     *     System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId());
     * }
     * 
* * * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of all of the {@link DeletedSecret deleted secrets} in the vault. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedSecrets(Context context) { return new PagedIterable<>(maxResults -> mapDeletedSecretItemPage(implClient.getDeletedSecretsSinglePage( vaultUrl, maxResults, context)), (continuationToken, maxResults) -> mapDeletedSecretItemPage(implClient.getDeletedSecretsNextSinglePage( continuationToken, vaultUrl, context))); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * *

Code sample

*

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it * out.

* *
     * for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) {
     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
     *     System.out.printf("Received secret's version with name %s and value %s",
     *         secretWithValue.getName(), secretWithValue.getValue());
     * }
     * 
* * * @param name The name of the secret. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecretVersions(String name) { return listPropertiesOfSecretVersions(name, Context.NONE); } /** * Lists all versions of the specified secret. Each {@link SecretProperties secret} returned only has its identifier * and attributes populated. The secret values and secret versions are not listed in the response. * This operation requires the {@code secrets/list} permission. * *

Code sample

*

The sample below fetches all versions of the given secret. For each secret version retrieved, makes a call * to {@link #getSecret(String, String) getSecret(String, String)} to get the version's value, and then prints it * out.

* *
     * for (SecretProperties secret : secretClient
     *     .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) {
     *     KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion());
     *     System.out.printf("Received secret's version with name %s and value %s",
     *         secretWithValue.getName(), secretWithValue.getValue());
     * }
     * 
* * *

Iterate over secret versions by page

*

The sample below iterates over each {@link SecretProperties secret} by each page and calls * {@link SecretClient#getSecret(String, String)}. This will return the {@link KeyVaultSecret secret} with the * corresponding version's value.

* * *
     * secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2))
     *     .iterableByPage().forEach(resp -> {
     *         System.out.printf("Got response headers . Url: %s, Status code: %d %n",
     *             resp.getRequest().getUrl(), resp.getStatusCode());
     *         resp.getItems().forEach(value -> {
     *             KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion());
     *             System.out.printf("Received secret's version with name %s and value %s",
     *                 secretWithValue.getName(), secretWithValue.getValue());
     *         });
     *     });
     * 
* * * @param name The name of the secret. * @param context Additional context that is passed through the HTTP pipeline during the service call. * @return {@link PagedIterable} of {@link SecretProperties} of all the versions of the specified secret in the * vault. List is empty if secret with {@code name} does not exist in key vault * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpResponseException when a secret with {@code name} is empty string. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecretVersions(String name, Context context) { return new PagedIterable<>(maxResults -> mapSecretItemPage(implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), (continuationToken, maxResults) -> mapSecretItemPage(implClient.getSecretVersionsNextSinglePage( continuationToken, vaultUrl, context))); } private static T callWithMappedException(Supplier call, Function exceptionMapper) { try { return call.get(); } catch (KeyVaultErrorException ex) { throw exceptionMapper.apply(ex); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy