Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kv secrets samples and readme #3892

Merged
merged 16 commits into from
Jun 20, 2019
337 changes: 337 additions & 0 deletions keyvault/client/secrets/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import com.azure.keyvault.SecretClient;
import com.azure.keyvault.models.Secret;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.OffsetDateTime;

/**
* Sample demonstrates how to backup and restore secrets in the key vault.
*/
public class BackupAndRestoreOperations {
/**
* Authenticates with the key vault and shows how to backup and restore secrets in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {

// Instantiate a client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
SecretClient client = SecretClient.builder()
.endpoint("https://{YOUR_VAULT_NAME}.vault.azure.net")
//.credential(AzureCredential.DEFAULT)
.build();

// Let's create secrets holding storage account credentials valid for 1 year. if the secret
// already exists in the key vault, then a new version of the secret is created.
client.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.expires(OffsetDateTime.now().plusYears(1)));

// Backups are good to have, if in case secrets get accidentally deleted by you.
// For long term storage, it is ideal to write the backup to a file.
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
byte[] secretBackup = client.backupSecret("StorageAccountPassword").value();
writeBackupToFile(secretBackup, backupFilePath);

// The storage account secret is no longer in use, so you delete it.
client.deleteSecret("StorageAccountPassword");

//To ensure secret is deleted on server side.
Thread.sleep(30000);

// If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion.
client.purgeDeletedSecret("StorageAccountPassword");

//To ensure secret is purged on server side.
Thread.sleep(15000);

// After sometime, the secret is required again. We can use the backup value to restore it in the key vault.
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
Secret restoredSecret = client.restoreSecret(backupFromFile).value();
}

private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
// Close the file
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import com.azure.keyvault.SecretAsyncClient;
import com.azure.keyvault.models.Secret;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.OffsetDateTime;

/**
* Sample demonstrates how to asynchronously backup and restore secrets in the key vault.
*/
public class BackupAndRestoreOperationsAsync {
/**
* Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
* @throws IOException when writing backup to file is unsuccessful.
*/
public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException {

// Instantiate async secret client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
SecretAsyncClient secretAsyncClient = SecretAsyncClient.builder()
.endpoint("https://{YOUR_VAULT_NAME}.vault.azure.net")
//.credential(AzureCredential.DEFAULT)
.build();

// Let's create secrets holding storage account credentials valid for 1 year. if the secret
// already exists in the key vault, then a new version of the secret is created.
secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.expires(OffsetDateTime.now().plusYears(1)))
.subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Thread.sleep(2000);

// Backups are good to have, if in case secrets get accidentally deleted by you.
// For long term storage, it is ideal to write the backup to a file.
String backupFilePath = "YOUR_BACKUP_FILE_PATH";
secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> {
byte[] backupBytes = backupResponse.value();
writeBackupToFile(backupBytes, backupFilePath);
});

Thread.sleep(7000);

// The storage account secret is no longer in use, so you delete it.
secretAsyncClient.deleteSecret("StorageAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.value().recoveryId()));

//To ensure file is deleted on server side.
Thread.sleep(30000);

// If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion.
secretAsyncClient.purgeDeletedSecret("StorageAccountPassword").subscribe(purgeResponse ->
System.out.printf("Purge Status response %d \n", purgeResponse.statusCode()));

//To ensure file is purged on server side.
Thread.sleep(15000);

// After sometime, the secret is required again. We can use the backup value to restore it in the key vault.
byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath());
secretAsyncClient.restoreSecret(backupFromFile).subscribe(secretResponse ->
System.out.printf("Restored Secret with name %s \n", secretResponse.value().name()));

//To ensure secret is restored on server side.
Thread.sleep(15000);
}

private static void writeBackupToFile(byte[] bytes, String filePath) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
OutputStream os = new FileOutputStream(file);
os.write(bytes);
System.out.println("Successfully wrote backup to file.");
// Close the file
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
62 changes: 62 additions & 0 deletions keyvault/client/secrets/src/samples/java/HelloWorld.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import com.azure.keyvault.SecretClient;
import com.azure.keyvault.models.Secret;
import com.azure.keyvault.models.SecretBase;
import java.time.OffsetDateTime;

/**
* Sample demonstrates how to set, get, update and delete a secret.
*/
public class HelloWorld {

/**
* Authenticates with the key vault and shows how to set, get, update and delete a secret in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
public static void main(String[] args) throws InterruptedException, IllegalArgumentException {

// Instantiate a secret client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
SecretClient secretClient = SecretClient.builder()
.endpoint("https://{YOUR_VAULT_NAME}.vault.azure.net")
//.credential(AzureCredential.DEFAULT)
.build();

// Let's create a secret holding bank account credentials valid for 1 year. if the secret
// already exists in the key vault, then a new version of the secret is created.
secretClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.expires(OffsetDateTime.now().plusYears(1)));

// Let's Get the bank secret from the key vault.
Secret bankSecret = secretClient.getSecret("BankAccountPassword").value();
System.out.printf("Secret is returned with name %s and value %s \n", bankSecret.name(), bankSecret.value());

// After one year, the bank account is still active, we need to update the expiry time of the secret.
// The update method can be used to update the expiry attribute of the secret. It cannot be used to update
// the value of the secret.
bankSecret.expires(bankSecret.expires().plusYears(1));
SecretBase updatedSecret = secretClient.updateSecret(bankSecret).value();
System.out.printf("Secret's updated expiry time %s \n", updatedSecret.expires());

// Bank forced a password update for security purposes. Let's change the value of the secret in the key vault.
// To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot
// change the value of the secret.
secretClient.setSecret(new Secret("BankAccountPassword", "bhjd4DDgsa")
.expires(OffsetDateTime.now().plusYears(1)));

// The bank account was closed, need to delete its credentials from the key vault.
secretClient.deleteSecret("BankAccountPassword");

// To ensure secret is deleted on server side.
Thread.sleep(30000);

// If the keyvault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged.
secretClient.purgeDeletedSecret("BankAccountPassword");
}
}
78 changes: 78 additions & 0 deletions keyvault/client/secrets/src/samples/java/HelloWorldAsync.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import com.azure.keyvault.SecretAsyncClient;
import com.azure.keyvault.models.Secret;
import java.time.OffsetDateTime;

/**
* Sample demonstrates how to asynchronously set, get, update and delete a secret.
*/
public class HelloWorldAsync {
/**
* Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
* @throws InterruptedException when the thread is interrupted in sleep mode.
*/
public static void main(String[] args) throws InterruptedException {

// Instantiate an async secret client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
SecretAsyncClient secretAsyncClient = SecretAsyncClient.builder()
.endpoint("https://{YOUR_VAULT_NAME}.vault.azure.net")
//.credential(AzureCredential.DEFAULT)
.build();

// Let's create a secret holding bank account credentials valid for 1 year. if the secret
// already exists in the key vault, then a new version of the secret is created.
secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.expires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Thread.sleep(2000);

// Let's Get the bank secret from the key vault.
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse ->
System.out.printf("Secret returned with name %s , value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Thread.sleep(2000);

// After one year, the bank account is still active, we need to update the expiry time of the secret.
// The update method can be used to update the expiry attribute of the secret. It cannot be used to update
// the value of the secret.
secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> {
Secret secret = secretResponse.value();
//Update the expiry time of the secret.
secret.expires(secret.expires().plusYears(1));
secretAsyncClient.updateSecret(secret).subscribe(updatedSecretResponse ->
System.out.printf("Secret's updated expiry time %s \n", updatedSecretResponse.value().expires().toString()));
});

Thread.sleep(2000);

// Bank forced a password update for security purposes. Let's change the value of the secret in the key vault.
// To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot
// change the value of the secret.
secretAsyncClient.setSecret("BankAccountPassword", "bhjd4DDgsa").subscribe(secretResponse ->
System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));

Thread.sleep(2000);

// The bank account was closed, need to delete its credentials from the key vault.
secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse ->
System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.value().recoveryId()));

//To ensure secret is deleted on server side.
Thread.sleep(30000);

// If the keyvault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged.
secretAsyncClient.purgeDeletedSecret("BankAccountPassword").subscribe(purgeResponse ->
System.out.printf("Bank account secret purge status response %d \n", purgeResponse.statusCode()));

//To ensure secret is purged on server side.
Thread.sleep(15000);
}
}
49 changes: 49 additions & 0 deletions keyvault/client/secrets/src/samples/java/ListOperations.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import com.azure.keyvault.SecretClient;
import com.azure.keyvault.models.Secret;
import java.time.OffsetDateTime;

/**
* Sample demonstrates how to list secrets and versions of a given secret in the key vault.
*/
public class ListOperations {
/**
* Authenticates with the key vault and shows how to list secrets and list versions of a specific secret in the key vault.
*
* @param args Unused. Arguments to the program.
* @throws IllegalArgumentException when invalid key vault endpoint is passed.
*/
public static void main(String[] args) throws IllegalArgumentException {

// Instantiate a client that will be used to call the service. Notice that the client is using default Azure
// credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
// 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
SecretClient client = SecretClient.builder()
.endpoint("https://{YOUR_VAULT_NAME}.vault.azure.net")
//.credential(AzureCredential.DEFAULT)
.build();

// Let's create secrets holding storage and bank accounts credentials valid for 1 year. if the secret
// already exists in the key vault, then a new version of the secret is created.
client.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf")
.expires(OffsetDateTime.now().plusYears(1)));

client.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v")
.expires(OffsetDateTime.now().plusYears(1)));

// You need to check if any of the secrets are sharing same values. Let's list the secrets and print their values.
// 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.
client.listSecrets().stream().map(client::getSecret).forEach(secretResponse ->
System.out.printf("Received secret with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));

// The bank account password got updated, so you want to update the secret in key vault to ensure it reflects the new password.
// Calling setSecret on an existing secret creates a new version of the secret in the key vault with the new value.
client.setSecret("BankAccountPassword", "sskdjfsdasdjsd");

// You need to check all the different values your bank account password secret had previously. Lets print all the versions of this secret.
client.listSecretVersions("BankAccountPassword").stream().map(client::getSecret).forEach(secretResponse ->
System.out.printf("Received secret's version with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()));
}
}
Loading