Azure Key Vault Administration library for Java
Azure Key Vault Managed HSM is a fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs.
The Azure Key Vault Administration library clients support administrative tasks such as full backup/restore and key-level role-based access control (RBAC).
Source code | API reference documentation | Product documentation | Samples
Getting started
Include the package
Include the BOM file
Please include the azure-sdk-bom
to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. To learn more about the BOM, see the AZURE SDK BOM README.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>{bom_version_to_target}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
and then include the direct dependency in the dependencies section without the version tag as shown below.
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-security-keyvault-administration</artifactId>
</dependency>
</dependencies>
Include direct dependency
If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-security-keyvault-administration</artifactId>
<version>4.6.1</version>
</dependency>
Prerequisites
- A Java Development Kit (JDK), version 8 or later.
- Here are details about Java 8 client compatibility with Azure Certificate Authority.
- An Azure Subscription.
- An existing Azure Key Vault Managed HSM. If you need to create a Managed HSM, you can do so using the Azure CLI by following the steps in this document.
Authenticate the client
In order to interact with the Azure Key Vault service, you will need to create an instance of either the KeyVaultAccessControlClient
class or the KeyVaultBackupClient
class, as well as a vault url (which you may see as "DNS Name" in the Azure Portal) and a credential object. The examples shown in this document use a credential object named 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.
Create an access control client
Once you perform the authentication set up that suits you best and replaced your-managed-hsm-url with the URL for your key vault, you can create the KeyVaultAccessControlClient
:
KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()
.vaultUrl("<your-managed-hsm-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
NOTE: For using an asynchronous client use
KeyVaultAccessControlAsyncClient
instead ofKeyVaultAccessControlClient
and callbuildAsyncClient()
.
Create a backup client
Once you perform the authentication set up that suits you best and replaced your-managed-hsm-url with the URL for your key vault, you can create the KeyVaultBackupClient
:
KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
.vaultUrl("<your-managed-hsm-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
NOTE: For using an asynchronous client use
KeyVaultBackupAsyncClient
instead ofKeyVaultBackupClient
and callbuildAsyncClient()
.
Create a settings client
Once you perform the authentication set up that suits you best and replaced your-managed-hsm-url with the URL for your key vault, you can create the KeyVaultSettingsClient
:
KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder()
.vaultUrl("<your-managed-hsm-url>")
.credential(new DefaultAzureCredentialBuilder().build())
.buildClient();
NOTE: For using an asynchronous client use
KeyVaultSettingsAsyncClient
instead ofKeyVaultSettingsClient
and callbuildAsyncClient()
.
Key concepts
Key Vault Access Control client
The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting, setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous (KeyVaultAccessControlAsyncClient
) and synchronous (KeyVaultAccessControlClient
) clients exist in the SDK allowing for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can interact with the primary resource types in Key Vault.
Role Definition
A role definition is a collection of permissions. It defines the operations that can be performed, such as read, write, and delete. It can also define the operations that are excluded from allowed operations.
Role definitions can be listed and specified as part of a role assignment.
Role Assignment
A role assignment is the association of a role definition to a service principal. They can be created, listed, fetched individually, and deleted.
Key Vault Backup client
The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key backups, full key restores, and selective key restores. Asynchronous (KeyVaultBackupAsyncClient
) and synchronous (KeyVaultBackupClient
) clients exist in the SDK allowing for the selection of a client based on an application's use case.
NOTE: The backing store for key backups is a blob storage container using Shared Access Signature authentication. For more details on creating a SAS token using the
BlobServiceClient
, see the Azure Storage Blobs client README. Alternatively, it is possible to generate a SAS token in Storage Explorer.
Backup Operation
A backup operation represents a long-running operation for a full key backup.
Restore Operation
A restore operation represents a long-running operation for both a full key and selective key restore.
Key Vault Settings client
The Key Vault Access Control client allows manipulation of an Azure Key Vault account's settings, with operations such as: getting, updating, and listing. Asynchronous (KeyVaultSettingsAsyncClient
) and synchronous (KeyVaultSettingsClient
) clients exist in the SDK allowing for the selection of a client based on an application's use case.
Access control operations
Examples
Sync API
The following sections provide several code snippets covering some of the most common Azure Key Vault Access Control service tasks, including:
- List role definitions
- Create or update a role definition
- Retrieve a role definition
- List role assignments
- Create a role assignment
- Retrieve a role assignment
- Delete a role assignment
List role definitions
List the role definitions in the key vault by calling listRoleDefinitions()
.
PagedIterable<KeyVaultRoleDefinition> roleDefinitions =
keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL);
roleDefinitions.forEach(roleDefinition ->
System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName()));
Create or update a role definition
Create or update a role definition in the key vault. The following example shows how to create a role definition with a randomly generated name.
KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL);
System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",
roleDefinition.getName(), roleDefinition.getRoleName());
Retrieve a role definition
Get an existing role definition. To do this, the scope and 'name' property from an existing role definition are required.
String roleDefinitionName = "<role-definition-name>";
KeyVaultRoleDefinition roleDefinition =
keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),
roleDefinition.getRoleName());
Delete a role definition
Delete a role definition. To do this, the scope and 'name' property property from an existing role definition are required.
String roleDefinitionName = "<role-definition-name>";
keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);
System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);
List role assignments
List the role assignments in the key vault by calling listRoleAssignments()
.
PagedIterable<KeyVaultRoleAssignment> roleAssignments =
keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL);
roleAssignments.forEach(roleAssignment ->
System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
Create a role assignment
Create a role assignment in the key vault. To do this a role definition ID and a service principal object ID are required.
A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleDefinitions()
.
See the Create/Get Credentials section for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command:
az ad signed-in-user show --query objectId
String roleDefinitionId = "<role-definition-id>";
String servicePrincipalId = "<service-principal-id>";
KeyVaultRoleAssignment roleAssignment =
keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,
servicePrincipalId);
System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n",
roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId());
Retrieve a role assignment
Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required.
String roleAssignmentName = "<role-assignment-name>";
KeyVaultRoleAssignment roleAssignment =
keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName());
Delete a role assignment
To remove a role assignment from a service principal, the role assignment must be deleted. To do this, the 'name' property from an existing role assignment is required.
String roleAssignmentName = "<role-assignment-name>";
keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);
System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);
Async API
The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Access Control service tasks, including:
- List role definitions asynchronously
- Create or update a role definition asynchronously
- Retrieve a role definition asynchronously
- Delete a role definition asynchronously
- List role assignments asynchronously
- Create a role assignment asynchronously
- Retrieve a role assignment asynchronously
- Delete a role assignment asynchronously
Note : You should add
System.in.read()
orThread.sleep()
after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits.
List role definitions asynchronously
List the role definitions in the key vault by calling listRoleDefinitions()
.
keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)
.subscribe(roleDefinition ->
System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName()));
Create or update a role definition asynchronously
Create or update a role definition in the key vault. The following example shows how to create a role definition with a randomly generated name.
keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL)
.subscribe(roleDefinition ->
System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",
roleDefinition.getName(), roleDefinition.getRoleName()));
Retrieve a role definition asynchronously
Get an existing role definition. To do this, the 'name' property from an existing role definition is required.
String roleDefinitionName = "<role-definition-name>";
keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
.subscribe(roleDefinition ->
System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n",
roleDefinition.getName(), roleDefinition.getRoleName()));
Delete a role definition asynchronously
Delete a role definition. To do this, the 'name' property from an existing role definition is required.
String roleDefinitionName = "<role-definition-name>";
keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName)
.subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName));
List role assignments asynchronously
List the role assignments in the key vault by calling listRoleAssignments()
.
keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)
.subscribe(roleAssignment ->
System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
Create a role assignment asynchronously
Create a role assignment in the key vault. To do this a role definition ID and a service principal object ID are required.
A role definition ID can be obtained from the 'id' property of one of the role definitions returned from listRoleDefinitions()
.
See the Create/Get Credentials section for links and instructions on how to generate a new service principal and obtain it's object ID. You can also get the object ID for your currently signed in account by running the following Azure CLI command:
az ad signed-in-user show --query objectId
String roleDefinitionId = "<role-definition-id>";
String servicePrincipalId = "<service-principal-id>";
keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,
servicePrincipalId).subscribe(roleAssignment ->
System.out.printf("Created role assignment with randomly generated name '%s' for principal with id"
+ "'%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()));
Retrieve a role assignment asynchronously
Get an existing role assignment. To do this, the 'name' property from an existing role assignment is required.
String roleAssignmentName = "<role-assignment-name>";
keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName)
.subscribe(roleAssignment ->
System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()));
Delete a role assignment asynchronously
To remove a role assignment from a service principal, the role assignment must be deleted. To do this, the 'name' property from an existing role assignment is required.
String roleAssignmentName = "<role-assignment-name>";
keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName)
.subscribe(unused ->
System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName));
Backup and restore operations
Examples
Sync API
The following sections provide several code snippets covering some of the most common Azure Key Vault Backup client tasks, including:
Backup a collection of keys
Back up an entire collection of keys using beginBackup()
.
String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
String sasToken = "<sas-token>";
SyncPoller<KeyVaultBackupOperation, String> backupPoller =
keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken);
PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();
if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
String folderUrl = backupPoller.getFinalResult();
System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);
} else {
KeyVaultBackupOperation operation = backupPoller.poll().getValue();
System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());
}
Restore a collection of keys
Restore an entire collection of keys from a backup using beginRestore()
.
String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
String sasToken = "<sas-token>";
SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> restorePoller =
keyVaultBackupClient.beginRestore(folderUrl, sasToken);
PollResponse<KeyVaultRestoreOperation> pollResponse = restorePoller.poll();
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
PollResponse<KeyVaultRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
System.out.printf("Backup restored successfully.%n");
} else {
KeyVaultRestoreOperation operation = restorePoller.poll().getValue();
System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());
}
Selectively restore a key
Restore a specific key from a backup using beginSelectiveRestore()
.
String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
String sasToken = "<sas-token>";
String keyName = "myKey";
SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> restorePoller =
keyVaultBackupClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);
PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = restorePoller.poll();
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());
PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = restorePoller.waitForCompletion();
if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
System.out.printf("Key restored successfully.%n");
} else {
KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue();
System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());
}
Async API
The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Backup client tasks, including:
Note : You should add
System.in.read()
orThread.sleep()
after the function calls in the main class/thread to allow async functions/operations to execute and finish before the main application/thread exits.
Backup a collection of keys asynchronously
Back up an entire collection of keys using beginBackup()
.
String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";
String sasToken = "<sas-token>";
keyVaultBackupAsyncClient.beginBackup(blobStorageUrl, sasToken)
.setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
.doOnError(e -> System.out.printf("Backup failed with error: %s.%n", e.getMessage()))
.doOnNext(pollResponse ->
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
.filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(folderUrl ->
System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl));
Restore a collection of keys asynchronously
Restore an entire collection of keys from a backup using beginRestore()
.
String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
String sasToken = "<sas-token>";
keyVaultBackupAsyncClient.beginRestore(folderUrl, sasToken)
.setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
.doOnError(e -> System.out.printf("Restore failed with error: %s.%n", e.getMessage()))
.doOnNext(pollResponse ->
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
.filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(unused -> System.out.printf("Backup restored successfully.%n"));
Selectively restore a key asynchronously
Restore an entire collection of keys from a backup using beginSelectiveRestore()
.
String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";
String sasToken = "<sas-token>";
String keyName = "myKey";
keyVaultBackupAsyncClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName)
.setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval.
.doOnError(e -> System.out.printf("Key restoration failed with error: %s.%n", e.getMessage()))
.doOnNext(pollResponse ->
System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()))
.filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)
.flatMap(AsyncPollResponse::getFinalResult)
.subscribe(unused -> System.out.printf("Key restored successfully.%n"));
Settings operations
Examples
Sync API
The following sections provide several code snippets covering some of the most common Azure Key Vault Settings client tasks, including:
Get all settings
List all the settings for an Azure Key Vault account.
KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();
for (KeyVaultSetting setting : getSettingsResult.getSettings()) {
System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());
}
Retrieve a specific setting
Retrieve a specific setting.
String settingName = "<setting-to-get>";
KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);
System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(),
setting.asBoolean());
Update a specific setting
Update a specific setting.
String settingName = "<setting-to-update>";
KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);
System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());
Async API
The following sections provide several code snippets covering some of the most common asynchronous Azure Key Vault Settings client tasks, including:
Get all settings asynchronously
List all the settings for a Key Vault account.
keyVaultSettingsAsyncClient.getSettings()
.subscribe(settingsResult ->
settingsResult.getSettings().forEach(setting ->
System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(),
setting.asBoolean())));
Retrieve a specific setting asynchronously
Retrieve a specific setting.
String settingName = "<setting-to-get>";
keyVaultSettingsAsyncClient.getSetting(settingName)
.subscribe(setting ->
System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(),
setting.asBoolean()));
Update a specific setting asynchronously
Update a specific setting.
String settingName = "<setting-to-update>";
KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);
keyVaultSettingsAsyncClient.updateSetting(settingToUpdate)
.subscribe(updatedSetting ->
System.out.printf("Updated setting with name '%s' and value '%s'.%n", updatedSetting.getName(),
updatedSetting.asBoolean()));
Troubleshooting
See our troubleshooting guide for details on how to diagnose various failure scenarios.
General
Azure Key Vault Access Control clients raise exceptions. For example, if you try to retrieve a role assignment after it is deleted a 404
error is returned, indicating the resource was not found. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.
try {
keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, "<role-assginment-name>");
} catch (HttpResponseException e) {
System.out.println(e.getMessage());
}
Default HTTP client
All client libraries by default use the Netty HTTP client. Adding the above dependency will automatically configure the client library to use the Netty HTTP client. Configuring or changing the HTTP client is detailed in the HTTP clients wiki.
Default SSL library
All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an Uber JAR containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the performance tuning section of the wiki.
Next steps
Several Key Vault 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 Azure Key Vault.
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 opencode@microsoft.com with any additional questions or comments.
Azure SDK for Java