快速入门:适用于 Java 的 Azure Key Vault 客户端库Quickstart: Azure Key Vault client library for Java

适用于 Java 的 Azure Key Vault 客户端库入门。Get started with the Azure Key Vault client library for Java. 请遵循以下步骤安装包并试用基本任务的示例代码。Follow the steps below to install the package and try out example code for basic tasks.

Azure 密钥保管库可帮助保护云应用程序和服务使用的加密密钥和机密。Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. 使用适用于 Java 的 Key Vault 客户端库可以:Use the Key Vault client library for Java to:

  • 提高安全性以及控制密钥和密码。Increase security and control over keys and passwords.
  • 在几分钟内创建并导入加密密钥。Create and import encryption keys in minutes.
  • 通过云扩展和全局冗余减少延迟。Reduce latency with cloud scale and global redundancy.
  • 简化和自动化与 TLS/SSL 证书相关的任务。Simplify and automate tasks for TLS/SSL certificates.

其他资源:Additional resources:

先决条件Prerequisites

本快速入门假设你在 Linux 终端窗口中运行 Azure CLIApache MavenThis quickstart assumes you are running Azure CLI and Apache Maven in a Linux terminal window.

设置Setting up

创建新的 Java 控制台应用Create new Java console app

在控制台窗口中,使用 mvn 命令创建名为 akv-java 的新 Java 控制台应用。In a console window, use the mvn command to create a new Java console app with the name akv-java.

mvn archetype:generate -DgroupId=com.keyvault.quickstart
                       -DartifactId=akv-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.quickstart
[INFO] Parameter: artifactId, Value: akv-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.keyvault.quickstart
[INFO] Parameter: packageInPathFormat, Value: com/keyvault/quickstart
[INFO] Parameter: package, Value: com.keyvault.quickstart
[INFO] Parameter: groupId, Value: com.keyvault.quickstart
[INFO] Parameter: artifactId, Value: akv-java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Project created from Archetype in dir: /home/user/quickstarts/akv-java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  38.124 s
[INFO] Finished at: 2019-11-15T13:19:06-08:00
[INFO] ------------------------------------------------------------------------

将目录更改为新创建的 akv-java/文件夹。Change your directory to the newly created akv-java/ folder.

cd akv-java

安装包Install the package

在文本编辑器中打开 pom.xml 文件。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.0.0</version>
    </dependency>

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

创建资源组和 Key VaultCreate a resource group and key vault

本快速入门使用预先创建的 Azure Key Vault。This quickstart uses a pre-created Azure key vault. 可以遵循 Azure CLI 快速入门Azure PowerShell 快速入门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. 或者,可运行以下 Azure CLI 命令。Alternatively, you can run the Azure CLI commands below.

重要

每个密钥保管库必须具有唯一的名称。Each key vault must have a unique name. 在以下示例中,将 替换为密钥保管库的名称。Replace with the name of your key vault in the following examples.

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

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

创建服务主体Create a service principal

对基于云的应用程序进行身份验证的最简单方法是使用托管标识;有关详细信息,请参阅使用应用服务托管标识访问 Azure Key VaultThe simplest way to authenticate a cloud-based application is with a managed identity; see Use an App Service managed identity to access Azure Key Vault for details.

不过,为了简单起见,本快速入门创建了一个需要使用服务主体和访问控制策略的桌面应用程序。For the sake of simplicity however, this quickstart creates a desktop application, which requires the use of a service principal and an access control policy. 服务主体要求使用格式为“http://<my-unique-service-principal-name>”的唯一名称。Your service principal requires a unique name in the format "http://<my-unique-service-principal-name>".

使用 Azure CLI az ad sp create-for-rbac 命令创建服务主体:Create a service principal using the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://&lt;my-unique-service-principal-name&gt;" --sdk-auth

此操作将返回一系列键/值对。This operation will return a series of key / value pairs.

{
  "clientId": "7da18cae-779c-41fc-992e-0527854c6583",
  "clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
  "subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
  "tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
  "activeDirectoryEndpointUrl": "https://login.chinacloudapi.cn",
  "resourceManagerEndpointUrl": "https://management.chinacloudapi.cn",
  "sqlManagementEndpointUrl": "https://management.core.chinacloudapi.cn:8443/",
  "galleryEndpointUrl": "https://gallery.chinacloudapi.cn/",
  "managementEndpointUrl": "https://management.core.chinacloudapi.cn/"
}

请记下 clientId、clientSecret 和 tenantId,因为我们将在下两个步骤中使用它们。Take note of the clientId, clientSecret, and tenantId, as we will use them in the next two steps.

为服务主体授予对 Key Vault 的访问权限Give the service principal access to your key vault

通过将 clientId 传递给 az keyvault set-policy 命令,为密钥保管库创建授予服务主体权限的访问策略。Create an access policy for your key vault that grants permission to your service principal by passing the clientId to the az keyvault set-policy command. 授予服务主体对密钥和机密的 get、list 和 set 权限。Give the service principal get, list, and set permissions for both keys and secrets.

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --secret-permissions delete get list set --key-permissions create decrypt delete encrypt get list unwrapKey wrapKey

设置环境变量Set environmental variables

应用程序中的 DefaultAzureCredential 方法依赖于三个环境变量:AZURE_CLIENT_IDAZURE_CLIENT_SECRETAZURE_TENANT_IDThe DefaultAzureCredential method in our application relies on three environmental variables: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. 使用将这些变量设置为在上述创建服务主体步骤中记下的 clientId、clientSecret 和 tenantId 值。use set these variables to the clientId, clientSecret, and tenantId values you noted in the Create a service principal step, above. 使用 export VARNAME=VALUE 格式设置环境变量。Use the export VARNAME=VALUE format to set your environmental variables. (该方法只为当前 shell 和从 shell 创建的进程设置变量;若要将这些变量永久添加到环境中,请编辑 /etc/environment 文件。)(This method only sets the variables for your current shell and processes created from the shell; to permanently add these variables to your environment, edit your /etc/environment file.)

还需要将密钥保管库名称另存为名为 KEY_VAULT_NAME 的环境变量。You will also need to save your key vault name as an environment variable called KEY_VAULT_NAME.

export AZURE_CLIENT_ID=<your-clientID>

export AZURE_CLIENT_SECRET=<your-clientSecret>

export AZURE_TENANT_ID=<your-tenantId>

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

对象模型Object model

使用适用于 Java 的 Azure Key Vault 客户端库可以管理密钥和相关的资产(例如证书和机密)。The Azure Key Vault client library for Java allows you to manage keys and related assets such as certificates and secrets. 以下代码示例演示如何创建客户端以及设置、检索和删除机密。The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret.

整个控制台应用在下面The entire console app is below.

代码示例Code examples

添加指令Add directives

将以下指令添加到代码的顶部:Add the following directives to the top of your code:

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.KeyVaultSecret;

进行身份验证并创建客户端Authenticate and create a client

向密钥保管库进行身份验证和创建密钥保管库客户端,依赖于上面设置环境变量步骤中的环境变量。Authenticating to your key vault and creating a key vault client depends on the environmental variables in the Set environmental variables step above. 密钥保管库的名称将扩展为密钥保管库 URI,格式为 https://<your-key-vault-name>.vault.azure.cnThe name of your key vault is expanded to the key vault URI, in the format https://<your-key-vault-name>.vault.azure.cn.

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

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

保存机密Save a secret

现在,应用程序已进行身份验证,可以使用 secretClient.setSecret 方法将机密放入 keyvault。Now that your application is authenticated, you can put a secret into your keyvault using the secretClient.setSecret method. 这要求提供机密名称 - 在此示例中,我们已将值“mySecret”分配给 secretName 变量。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));

可以使用 az keyvault secret show 命令来验证是否设置了机密:You can verify that the secret has been set with the az keyvault secret show command:

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

检索机密Retrieve a secret

现在,可以使用 secretClient.getSecret 方法检索以前设置的值。You can now retrieve the previously set value with the secretClient.getSecret method.

KeyVaultSecret retrievedSecret = secretClient.getSecret(secretName);

现可使用 retrievedSecret.getValue() 访问检索到的机密的值。You can now access the value of the retrieved secret with retrievedSecret.getValue().

删除机密Delete a secret

最后,使用 secretClient.beginDeleteSecret 方法从密钥保管库中删除机密。Finally, let's delete the secret from your key vault with the secretClient.beginDeleteSecret method.

secretClient.beginDeleteSecret(secretName);

可以使用 az keyvault secret show 命令来验证是否已删除机密:You can verify that the secret is gone with the az keyvault secret show command:

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

清理资源Clean up resources

可以使用 Azure CLI 或 Azure PowerShell 来删除不再需要的 Key Vault 和相应的资源组。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.quickstart;

import java.io.Console;   

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.KeyVaultSecret;

public class App {

    public static void main(String[] args) throws InterruptedException, IllegalArgumentException {

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

        System.out.printf("key vault name = %s and kv uri = %s \n", keyVaultName, kvUri);

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


        Console con = System.console();  

        String secretName = "mySecret";

        System.out.println("Input the value of your secret > ");
        String secretValue = con.readLine();

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

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

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

        System.out.println("Forgetting your secret.");
        secretValue = "";
        System.out.println("Your secret is '" + secretValue + "'.");

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

        KeyVaultSecret retrievedSecret = secretClient.getSecret(secretName);

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

        secretClient.beginDeleteSecret(secretName);

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


    }
}

后续步骤Next steps

在本快速入门中,你创建了一个 Key Vault、存储了一个机密,然后检索了该机密。In this quickstart you created a key vault, stored a secret, and retrieved that secret. 若要详细了解 Key Vault 以及如何将其与应用程序集成,请继续阅读以下文章。To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.