Muokkaa

Jaa


Quickstart: Azure Key Vault Secret client library for Java

Get started with the Azure Key Vault Secret client library for Java. Follow these steps to install the package and try out example code for basic tasks.

Tip

If you're working with Azure Key Vault Secrets resources in a Spring application, we recommend that you consider Spring Cloud Azure as an alternative. Spring Cloud Azure is an open-source project that provides seamless Spring integration with Azure services. To learn more about Spring Cloud Azure, and to see an example using Key Vault Secrets, see Load a secret from Azure Key Vault in a Spring Boot application.

Additional resources:

Prerequisites

This quickstart assumes you're running Azure CLI and Apache Maven in a Linux terminal window.

Setting up

This quickstart is using the Azure Identity library with Azure CLI to authenticate user to Azure Services. Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.

Sign in to Azure

  1. Run the login command.

    az login
    

    If the CLI can open your default browser, it will do so and load an Azure sign-in page.

    Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.

  2. Sign in with your account credentials in the browser.

Create a new Java console app

In a console window, use the mvn command to create a new Java console app with the name akv-secrets-java.

mvn archetype:generate -DgroupId=com.keyvault.secrets.quickstart
                       -DartifactId=akv-secrets-java
                       -DarchetypeArtifactId=maven-archetype-quickstart
                       -DarchetypeVersion=1.4
                       -DinteractiveMode=false

The output from generating the project will look something like this:

[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.keyvault.secrets.quickstart
[INFO] Parameter: artifactId, Value: akv-secrets-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.keyvault.secrets.quickstart
[INFO] Parameter: packageInPathFormat, Value: com/keyvault/quickstart
[INFO] Parameter: package, Value: com.keyvault.secrets.quickstart
[INFO] Parameter: groupId, Value: com.keyvault.secrets.quickstart
[INFO] Parameter: artifactId, Value: akv-secrets-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Project created from Archetype in dir: /home/user/quickstarts/akv-secrets-java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  38.124 s
[INFO] Finished at: 2019-11-15T13:19:06-08:00
[INFO] ------------------------------------------------------------------------

Change your directory to the newly created akv-secrets-java/ folder.

cd akv-secrets-java

Install the package

Open the pom.xml file in your text editor. Add the following dependency elements to the group of dependencies.

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-security-keyvault-secrets</artifactId>
      <version>4.2.3</version>
    </dependency>

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-identity</artifactId>
      <version>1.2.0</version>
    </dependency>

Create a resource group and key vault

This quickstart uses a precreated Azure key vault. You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart.

Alternatively, you can run these Azure CLI or Azure PowerShell commands.

Important

Each key vault must have a unique name. Replace <your-unique-keyvault-name> with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<your-unique-keyvault-name>" -g "myResourceGroup" --enable-rbac-authorization

Grant access to your key vault

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

az role assignment create --role "Key Vault Secrets Officer" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

Replace <upn>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Set environment variables

This application is using your key vault name as an environment variable called KEY_VAULT_NAME.

Windows

set KEY_VAULT_NAME=<your-key-vault-name>

Windows PowerShell

$Env:KEY_VAULT_NAME="<your-key-vault-name>"

macOS or Linux

export KEY_VAULT_NAME=<your-key-vault-name>

Object model

The Azure Key Vault Secret client library for Java allows you to manage secrets. The Code examples section shows how to create a client, set a secret, retrieve a secret, and delete a secret.

Code examples

Add directives

Add the following directives to the top of your code:

import com.azure.core.util.polling.SyncPoller;
import com.azure.identity.DefaultAzureCredentialBuilder;

import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.DeletedSecret;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;

Authenticate and create a client

Application requests to most Azure services must be authorized. Using the DefaultAzureCredential class is the recommended approach for implementing passwordless connections to Azure services in your code. DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.

In this quickstart, DefaultAzureCredential authenticates to key vault using the credentials of the local development user logged into the Azure CLI. When the application is deployed to Azure, the same DefaultAzureCredential code can automatically discover and use a managed identity that is assigned to an App Service, Virtual Machine, or other services. For more information, see Managed Identity Overview.

In this example, the name of your key vault is expanded to the key vault URI, in the format https://<your-key-vault-name>.vault.azure.net. For more information about authenticating to key vault, see Developer's Guide.

String keyVaultName = System.getenv("KEY_VAULT_NAME");
String keyVaultUri = "https://" + keyVaultName + ".vault.azure.net";

SecretClient secretClient = new SecretClientBuilder()
    .vaultUrl(keyVaultUri)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Save a secret

Now that your application is authenticated, you can put a secret into your key vault using the secretClient.setSecret method. This requires a name for the secret—we've assigned the value "mySecret" to the secretName variable in this sample.

secretClient.setSecret(new KeyVaultSecret(secretName, secretValue));

You can verify that the secret has been set with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-key-vault-name> --name mySecret

Retrieve a secret

You can now retrieve the previously set secret with the secretClient.getSecret method.

KeyVaultSecret retrievedSecret = secretClient.getSecret(secretName);

You can now access the value of the retrieved secret with retrievedSecret.getValue().

Delete a secret

Finally, let's delete the secret from your key vault with the secretClient.beginDeleteSecret method.

Secret deletion is a long running operation, for which you can poll its progress or wait for it to complete.

SyncPoller<DeletedSecret, Void> deletionPoller = secretClient.beginDeleteSecret(secretName);
deletionPoller.waitForCompletion();

You can verify that the secret has been deleted with the az keyvault secret show command:

az keyvault secret show --vault-name <your-unique-key-vault-name> --name mySecret

Clean up resources

When no longer needed, you can use the Azure CLI or Azure PowerShell to remove your key vault and the corresponding resource group.

az group delete -g "myResourceGroup"
Remove-AzResourceGroup -Name "myResourceGroup"

Sample code

package com.keyvault.secrets.quickstart;

import java.io.Console;

import com.azure.core.util.polling.SyncPoller;
import com.azure.identity.DefaultAzureCredentialBuilder;

import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.DeletedSecret;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;

public class App {
    public static void main(String[] args) throws InterruptedException, IllegalArgumentException {
        String keyVaultName = System.getenv("KEY_VAULT_NAME");
        String keyVaultUri = "https://" + keyVaultName + ".vault.azure.net";

        System.out.printf("key vault name = %s and key vault URI = %s \n", keyVaultName, keyVaultUri);

        SecretClient secretClient = new SecretClientBuilder()
            .vaultUrl(keyVaultUri)
            .credential(new DefaultAzureCredentialBuilder().build())
            .buildClient();

        Console con = System.console();

        String secretName = "mySecret";

        System.out.println("Please provide the value of your secret > ");

        String secretValue = con.readLine();

        System.out.print("Creating a secret in " + keyVaultName + " called '" + secretName + "' with value '" + secretValue + "' ... ");

        secretClient.setSecret(new KeyVaultSecret(secretName, secretValue));

        System.out.println("done.");
        System.out.println("Forgetting your secret.");

        secretValue = "";
        System.out.println("Your secret's value is '" + secretValue + "'.");

        System.out.println("Retrieving your secret from " + keyVaultName + ".");

        KeyVaultSecret retrievedSecret = secretClient.getSecret(secretName);

        System.out.println("Your secret's value is '" + retrievedSecret.getValue() + "'.");
        System.out.print("Deleting your secret from " + keyVaultName + " ... ");

        SyncPoller<DeletedSecret, Void> deletionPoller = secretClient.beginDeleteSecret(secretName);
        deletionPoller.waitForCompletion();

        System.out.println("done.");
    }
}

Next steps

In this quickstart, you created a key vault, stored a secret, retrieved it, and then deleted it. To learn more about Key Vault and how to integrate it with your applications, continue on to these articles.