Uredi

Deli z drugimi prek


Quickstart: Azure Key Vault Certificate client library for Java (Certificates)

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

Tip

If you're working with Azure Key Vault Certificates 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 Certificates, see Enable HTTPS in Spring Boot with Azure Key Vault certificates.

Additional resources:

Prerequisites

This quickstart assumes you are 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-certificates-java.

mvn archetype:generate -DgroupId=com.keyvault.certificates.quickstart
                       -DartifactId=akv-certificates-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.certificates.quickstart
[INFO] Parameter: artifactId, Value: akv-certificates-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.keyvault.certificates.quickstart
[INFO] Parameter: packageInPathFormat, Value: com/keyvault/quickstart
[INFO] Parameter: package, Value: com.keyvault.certificates.quickstart
[INFO] Parameter: groupId, Value: com.keyvault.certificates.quickstart
[INFO] Parameter: artifactId, Value: akv-certificates-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Project created from Archetype in dir: /home/user/quickstarts/akv-certificates-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-certificates-java/ folder.

cd akv-certificates-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-certificates</artifactId>
      <version>4.1.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 Certificate 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 Certificate client library for Java allows you to manage certificates. The Code examples section shows how to create a client, create a certificate, retrieve a certificate, and delete a certificate.

The entire console app is below.

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.certificates.CertificateClient;
import com.azure.security.keyvault.certificates.CertificateClientBuilder;
import com.azure.security.keyvault.certificates.models.CertificateOperation;
import com.azure.security.keyvault.certificates.models.CertificatePolicy;
import com.azure.security.keyvault.certificates.models.DeletedCertificate;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificate;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy;

Authenticate and create a client

Application requests to most Azure services must be authorized. Using the DefaultAzureCredential 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";

CertificateClient certificateClient = new CertificateClientBuilder()
    .vaultUrl(keyVaultUri)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Save a secret

Now that your application is authenticated, you can create a certificate in your key vault using the certificateClient.beginCreateCertificate method. This requires a name for the certificate and a certificate policy -- we've assigned the value "myCertificate" to the certificateName variable in this sample and use a default policy.

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

SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certificatePoller =
    certificateClient.beginCreateCertificate(certificateName, CertificatePolicy.getDefault());
certificatePoller.waitForCompletion();

You can obtain the certificate once creation has completed with via the following call:

KeyVaultCertificate createdCertificate = certificatePoller.getFinalResult();

Retrieve a certificate

You can now retrieve the previously created certificate with the certificateClient.getCertificate method.

KeyVaultCertificate retrievedCertificate = certificateClient.getCertificate(certificateName);

You can now access the details of the retrieved certificate with operations like retrievedCertificate.getName, retrievedCertificate.getProperties, etc. As well as its contents retrievedCertificate.getCer.

Delete a certificate

Finally, let's delete the certificate from your key vault with the certificateClient.beginDeleteCertificate method, which is also a long running operation.

SyncPoller<DeletedCertificate, Void> deletionPoller = certificateClient.beginDeleteCertificate(certificateName);
deletionPoller.waitForCompletion();

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.certificates.quickstart;

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

import com.azure.security.keyvault.certificates.CertificateClient;
import com.azure.security.keyvault.certificates.CertificateClientBuilder;
import com.azure.security.keyvault.certificates.models.CertificateOperation;
import com.azure.security.keyvault.certificates.models.CertificatePolicy;
import com.azure.security.keyvault.certificates.models.DeletedCertificate;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificate;
import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy;

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 kv uri = %s \n", keyVaultName, keyVaultUri);

        CertificateClient certificateClient = new CertificateClientBuilder()
            .vaultUrl(keyVaultUri)
            .credential(new DefaultAzureCredentialBuilder().build())
            .buildClient();

        String certificateName = "myCertificate";

        System.out.print("Creating a certificate in " + keyVaultName + " called '" + certificateName + " ... ");

        SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certificatePoller =
            certificateClient.beginCreateCertificate(certificateName, CertificatePolicy.getDefault());
        certificatePoller.waitForCompletion();

        System.out.print("done.");
        System.out.println("Retrieving certificate from " + keyVaultName + ".");

        KeyVaultCertificate retrievedCertificate = certificateClient.getCertificate(certificateName);

        System.out.println("Your certificate's ID is '" + retrievedCertificate.getId() + "'.");
        System.out.println("Deleting your certificate from " + keyVaultName + " ... ");

        SyncPoller<DeletedCertificate, Void> deletionPoller = certificateClient.beginDeleteCertificate(certificateName);
        deletionPoller.waitForCompletion();

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

Next steps

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