当前位置: 首页 > 工具软件 > vault13 > 使用案例 >

java获取keyvault_快速入门 - 适用于 Java 的 Azure Key Vault 机密客户端库 | Microsoft Docs...

洪弘壮
2023-12-01

您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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

10/20/2019

本文内容

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

其他资源:Additional resources:

先决条件Prerequisites

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

设置Setting up

本快速入门结合使用 Azure Identity 库和 Azure CLI,向 Azure 服务验证用户身份。This quickstart is using the Azure Identity library with Azure CLI to authenticate user to Azure Services. 开发人员还可以使用 Visual Studio 或 Visual Studio Code 来验证其调用。有关详细信息,请参阅使用 Azure Identity 客户端库对客户端进行身份验证。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.

登录 AzureSign in to Azure

运行 login 命令。Run the login command.

az login

如果 CLI 可以打开默认浏览器,它将这样做并加载 Azure 登录页。If the CLI can open your default browser, it will do so and load an Azure sign-in page.

否则,请在浏览器中打开 https://aka.ms/devicelogin,然后输入终端中显示的授权代码。Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.

在浏览器中使用帐户凭据登录。Sign in with your account credentials in the browser.

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

在控制台窗口中,使用 mvn 命令创建名为 akv-secrets-java 的新 Java 控制台应用。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] ------------------------------------------------------------------------

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

cd akv-secrets-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.

com.azure

azure-security-keyvault-secrets

4.2.3

com.azure

azure-identity

1.2.0

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

本快速入门使用预先创建的 Azure Key Vault。This quickstart uses a pre-created Azure key vault.

或者,只需运行以下 Azure CLI 或 Azure PowerShell 命令。Alternatively, you can simply run the Azure CLI or Azure PowerShell 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 "EastUS"

az keyvault create --name "" -g "myResourceGroup"

New-AzResourceGroup -Name myResourceGroup -Location EastUS

New-AzKeyVault -Name "" -ResourceGroupName "myResourceGroup" -Location "EastUS"

授予对 Key Vault 的访问权限Grant access to your key vault

针对密钥保管库创建一个访问策略,以便为用户帐户授予机密权限。Create an access policy for your key vault that grants secret permissions to your user account.

az keyvault set-policy --name --upn user@domain.com --secret-permissions delete get list set purge

设置环境变量Set environment variables

此应用程序使用密钥保管库名称作为名为 KEY_VAULT_NAME 的环境变量。This application is using your key vault name as an environment variable called KEY_VAULT_NAME.

WindowsWindows

set KEY_VAULT_NAME=

Windows PowerShellWindows PowerShell

$Env:KEY_VAULT_NAME=""

macOS 或 LinuxmacOS or Linux

export KEY_VAULT_NAME=

对象模型Object model

适用于 Java 的 Azure Key Vault 机密客户端库可用于管理机密。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.

整个控制台应用在下面。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.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

本快速入门使用登录用户向 Key Vault 进行身份验证,这是本地开发的首选方法。In this quickstart, a logged in user is used to authenticate to Key Vault, which is preferred method for local development. 对于部署到 Azure 的应用程序,应将托管标识分配给应用服务或虚拟机。For applications deployed to Azure, a Managed Identity should be assigned to an App Service or Virtual Machine. 有关详细信息,请参阅托管标识概述。For more information, see Managed Identity Overview.

在下面的示例中,密钥保管库的名称将扩展为密钥保管库 URI,格式为“https://.vault.azure.net”。In the example below, the name of your key vault is expanded to the key vault URI, in the format "https://.vault.azure.net". 此示例使用 'DefaultAzureCredential()' 类,该类允许在具有不同选项的不同环境中使用相同代码提供标识。This example is using the 'DefaultAzureCredential()' class, which allows to use the same code across different environments with different options to provide identity.

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

现在,应用程序已进行身份验证,你可使用 secretClient.setSecret 方法将机密放入密钥保管库。Now that your application is authenticated, you can put a secret into your key vault 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));

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

az keyvault secret show --vault-name --name mySecret

检索机密Retrieve a secret

现在,可使用 secretClient.getSecret 方法检索之前设置的机密。You can now retrieve the previously set secret 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.

删除机密的操作耗时很长,你可轮询其进度或等待操作完成。Secret deletion is a long running operation, for which you can poll its progress or wait for it to complete.

SyncPoller 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 --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.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 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. 若要详细了解 Key Vault 以及如何将其与应用程序集成,请继续阅读以下文章。To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.

 类似资料: