java获取keyvault_教程:在 Java Spring Boot 应用中使用 Azure 应用程序配置 Key Vault 引用 | Microsoft Docs...
您現在訪問的是微軟AZURE全球版技術文檔網站,若需要訪問由世紀互聯運營的MICROSOFT AZURE中國區技術文檔網站,請訪問 https://docs.azure.cn.
教程:在 Java Spring 應用中使用 Key Vault 引用Tutorial: Use Key Vault references in a Java Spring app
08/11/2020
本文內容
本教程介紹如何將 Azure 應用程序配置服務與 Azure Key Vault 配合使用。In this tutorial, you learn how to use the Azure App Configuration service together with Azure Key Vault. 應用程序配置和 Key Vault 是互補性的服務,大多數應用程序部署中會同時使用兩者。App Configuration and Key Vault are complementary services used side by side in most application deployments.
應用程序配置可以創建密鑰來引用存儲在 Key Vault 中的值,以幫助你結合使用這兩個服務。App Configuration helps you use the services together by creating keys that reference values stored in Key Vault. 當應用程序配置創建此類密鑰時,它會存儲 Key Vault 值的 URI,而不是值本身。When App Configuration creates such keys, it stores the URIs of Key Vault values rather than the values themselves.
應用程序使用應用程序配置客戶端提供程序檢索 Key Vault 引用,就如同檢索應用程序配置中存儲的任何其他密鑰一樣。Your application uses the App Configuration client provider to retrieve Key Vault references, just as it does for any other keys stored in App Configuration. 在這種情況下,存儲在應用程序配置中的值是引用 Key Vault 中的值的 URI。In this case, the values stored in App Configuration are URIs that reference the values in the Key Vault. 這些值不是 Key Vault 值或憑據。They are not Key Vault values or credentials. 由于客戶端提供程序將密鑰識別為 Key Vault 引用,因此它使用 Key Vault 來檢索其值。Because the client provider recognizes the keys as Key Vault references, it uses Key Vault to retrieve their values.
應用程序負責向應用程序配置和 Key Vault 進行適當的身份驗證。Your application is responsible for authenticating properly to both App Configuration and Key Vault. 這兩項服務不直接通信。The two services don't communicate directly.
本教程介紹如何在代碼中實現 Key Vault 引用。This tutorial shows you how to implement Key Vault references in your code. 它建立在快速入門中介紹的 Web 應用之上。It builds on the web app introduced in the quickstarts.
你可以使用任何代碼編輯器執行本教程中的步驟。You can use any code editor to do the steps in this tutorial. 例如,Visual Studio Code 是適用于 Windows、macOS 和 Linux 操作系統的跨平臺代碼編輯器。For example, Visual Studio Code is a cross-platform code editor that's available for the Windows, macOS, and Linux operating systems.
在本教程中,你將了解如何執行以下操作:In this tutorial, you learn how to:
創建一個應用程序配置密鑰,用于引用 Key Vault 中存儲的值Create an App Configuration key that references a value stored in Key Vault.
從 Java Spring 應用程序訪問此密鑰的值。Access the value of this key from a Java Spring application.
先決條件Prerequisites
Azure 訂閱 - 創建免費帳戶Azure subscription - create one for free
Apache Maven 版本 3.0 或更高版本。Apache Maven version 3.0 or above.
創建保管庫Create a vault
選擇 Azure 門戶左上角的“創建資源”選項:Select the Create a resource option in the upper-left corner of the Azure portal:
在搜索框中輸入 Key Vault。In the search box, enter Key Vault.
在結果列表中,選擇左側的“Key Vault” 。From the results list, select Key vaults on the left.
在“Key Vault”中選擇“添加”。In Key vaults, select Add.
在“創建 Key Vault”中的右側提供以下信息:On the right in Create key vault, provide the following information:
選擇“訂閱”以選擇訂閱。Select Subscription to choose a subscription.
在“資源組”中選擇“新建”,然后輸入資源組的名稱 。In Resource Group, select Create new and enter a resource group name.
在“Key Vault 名稱”中,必須輸入唯一的名稱。In Key vault name, a unique name is required. 對于本教程,請輸入 Contoso-vault2。For this tutorial, enter Contoso-vault2.
在“區域”下拉列表中,選擇一個位置。In the Region drop-down list, choose a location.
將“創建 Key Vault”的其他選項保留默認值。Leave the other Create key vault options with their default values.
選擇“創建” 。Select Create.
目前,只有你的 Azure 帳戶有權訪問這個新保管庫。At this point, your Azure account is the only one authorized to access this new vault.
向 Key Vault 添加機密Add a secret to Key Vault
只需執行幾個額外的步驟即可將機密添加到保管庫。To add a secret to the vault, you need to take just a few additional steps. 在本例中,我們將添加一條消息,用于測試 Key Vault 檢索功能。In this case, add a message that you can use to test Key Vault retrieval. 此消息名為 Message,我們將在其中存儲“Hello from Key Vault”值。The message is called Message, and you store the value "Hello from Key Vault" in it.
在 Key Vault 屬性頁中選擇“機密” 。From the Key Vault properties pages, select Secrets.
選擇“生成/導入”。Select Generate/Import.
在“創建機密”窗格中輸入以下值:In the Create a secret pane, enter the following values:
上傳選項:輸入 Manual。Upload options: Enter Manual.
Name:輸入 Message。Name: Enter Message.
值:輸入 Hello from Key Vault。Value: Enter Hello from Key Vault.
將“創建機密”的其他屬性保留默認值。Leave the other Create a secret properties with their default values.
選擇“創建” 。Select Create.
將 Key Vault 引用添加到應用程序配置Add a Key Vault reference to App Configuration
Sign in to the Azure portal. 選擇“所有資源”,然后選擇在快速入門中創建的應用程序配置存儲實例 。Select All resources, and then select the App Configuration store instance that you created in the quickstart.
選擇“配置資源管理器”。Select Configuration Explorer.
選擇“+ 創建” > “Key Vault 引用”,然后指定以下值:Select + Create > Key vault reference, and then specify the following values:
密鑰:選擇 /application/config.keyvaultmessageKey: Select /application/config.keyvaultmessage
標簽:將此值保留空白。Label: Leave this value blank.
“訂閱”、“資源組”和“Key Vault”: 輸入上一部分在密鑰保管庫中創建的值相對應的值。Subscription, Resource group, and Key vault: Enter the values corresponding to the values in the key vault you created in the previous section.
機密:選擇在上一部分創建的名為 Message 的機密。Secret: Select the secret named Message that you created in the previous section.
連接到 Key VaultConnect to Key Vault
在本教程中,我們將使用一個服務主體向 Key Vault 進行身份驗證。In this tutorial, you use a service principal for authentication to Key Vault. 若要創建該服務主體,請使用 Azure CLI az ad sp create-for-rbac 命令:To create this service principal, use the Azure CLI az ad sp create-for-rbac command:
az ad sp create-for-rbac -n "http://mySP" --sdk-auth
此操作返回一系列鍵/值對:This operation returns 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.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
運行以下命令,使服務主體能夠訪問 Key Vault:Run the following command to let the service principal access your key vault:
az keyvault set-policy -n --spn --secret-permissions delete get
運行以下命令獲取 object-id,然后將其添加到應用配置。Run the following command to get your object-id, then add it to App Configuration.
az ad sp show --id
az role assignment create --role "App Configuration Data Reader" --assignee-object-id --resource-group
創建環境變量 AZURE_CLIENT_ID、AZURE_CLIENT_SECRET 和 AZURE_TENANT_ID 。Create the environment variables AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. 使用上一步中顯示的服務主體的值。Use the values for the service principal that were displayed in the previous steps. 在命令行中,運行以下命令并重啟命令提示符,以使更改生效:At the command line, run the following commands and restart the command prompt to allow the change to take effect:
setx AZURE_CLIENT_ID "clientId"
setx AZURE_CLIENT_SECRET "clientSecret"
setx AZURE_TENANT_ID "tenantId"
如果使用 Windows PowerShell,請運行以下命令:If you use Windows PowerShell, run the following command:
$Env:AZURE_CLIENT_ID = "clientId"
$Env:AZURE_CLIENT_SECRET = "clientSecret"
$Env:AZURE_TENANT_ID = "tenantId"
如果使用 macOS 或 Linux,則請運行以下命令:If you use macOS or Linux, run the following command:
export AZURE_CLIENT_ID ='clientId'
export AZURE_CLIENT_SECRET ='clientSecret'
export AZURE_TENANT_ID ='tenantId'
備注
這些 Key Vault 憑據僅在應用程序中使用。These Key Vault credentials are only used within your application. 應用程序使用這些憑據直接通過 Key Vault 進行身份驗證,而不涉及應用配置服務。Your application authenticates directly with Key Vault using these credentials without involving the App Configuration service. Key Vault 同時為應用程序和應用配置服務提供身份驗證,而無需共享或公開密鑰。The Key Vault provides authentication for both your application and your App Configuration service without sharing or exposing keys.
更新代碼以使用 Key Vault 引用Update your code to use a Key Vault reference
創建一個名為“APP_CONFIGURATION_ENDPOINT” 的環境變量。Create an environment variable called APP_CONFIGURATION_ENDPOINT. 將其值設為你的應用配置存儲的終結點。Set its value to the endpoint of your App Configuration store. 可以在 Azure 門戶的“訪問密鑰” 邊欄選項卡上找到該終結點。You can find the endpoint on the Access Keys blade in the Azure portal. 重啟命令提示符以使更改生效。Restart the command prompt to allow the change to take effect.
打開“resources” 文件夾中的 bootstrap.properties 。Open bootstrap.properties in the resources folder. 更新此文件以使用 APP_CONFIGURATION_ENDPOINT 值。Update this file to use the APP_CONFIGURATION_ENDPOINT value. 刪除對此文件中的連接字符串的任何引用。Remove any references to a connection string in this file.
spring.cloud.azure.appconfiguration.stores[0].endpoint= ${APP_CONFIGURATION_ENDPOINT}
打開 MessageProperties.java 。Open MessageProperties.java. 添加一個名為“keyVaultMessage” 的新變量:Add a new variable called keyVaultMessage:
private String keyVaultMessage;
public String getKeyVaultMessage() {
return keyVaultMessage;
}
public void setKeyVaultMessage(String keyVaultMessage) {
this.keyVaultMessage = keyVaultMessage;
}
打開 HelloController.java 。Open HelloController.java. 更新 getMessage 方法,以包括從 Key Vault 檢索到的消息。Update the getMessage method to include the message retrieved from Key Vault.
@GetMapping
public String getMessage() {
return "Message: " + properties.getMessage() + "\nKey Vault message: " + properties.getKeyVaultMessage();
}
創建一個名為 AzureCredentials.java 的新文件并添加下面的代碼。Create a new file called AzureCredentials.java and add the code below.
package com.example.demo;
import com.azure.core.credential.TokenCredential;
import com.azure.identity.EnvironmentCredentialBuilder;
import com.microsoft.azure.spring.cloud.config.AppConfigurationCredentialProvider;
import com.microsoft.azure.spring.cloud.config.KeyVaultCredentialProvider;
public class AzureCredentials implements AppConfigurationCredentialProvider, KeyVaultCredentialProvider{
@Override
public TokenCredential getKeyVaultCredential(String uri) {
return getCredential();
}
@Override
public TokenCredential getAppConfigCredential(String uri) {
return getCredential();
}
private TokenCredential getCredential() {
return new EnvironmentCredentialBuilder().build();
}
}
創建一個名為 AppConfiguration.java 的新文件。Create a new file called AppConfiguration.java. 并添加以下代碼。And add the code below.
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfiguration {
@Bean
public AzureCredentials azureCredentials() {
return new AzureCredentials();
}
}
在資源 META-INF 目錄中創建一個名為 spring.factories 的新文件,然后添加以下代碼。Create a new file in your resources META-INF directory called spring.factories and add the code below.
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.example.demo.AppConfiguration
使用 Maven 生成 Spring Boot 應用程序,然后運行該程序,例如:Build your Spring Boot application with Maven and run it, for example:
mvn clean package
mvn spring-boot:run
應用程序運行以后,請使用 curl 測試該應用程序,例如 :After your application is running, use curl to test your application, for example:
curl -X GET http://localhost:8080/
可看到在應用程序配置存儲區中輸入的消息。You see the message that you entered in the App Configuration store. 還會看到你在 Key Vault 中輸入的消息。You also see the message that you entered in Key Vault.
清理資源Clean up resources
如果不想繼續使用本文中創建的資源,請刪除此處創建的資源組以避免產生費用。If you do not want to continue using the resources created in this article, delete the resource group you created here to avoid charges.
重要
刪除資源組的操作不可逆。Deleting a resource group is irreversible. 將永久刪除資源組以及其中的所有資源。The resource group and all the resources in it are permanently deleted. 請確保不要意外刪除錯誤的資源組或資源。Make sure that you don't accidentally delete the wrong resource group or resources. 如果在包含要保留的其他資源的資源組中創建了本文的資源,請從相應的窗格中單獨刪除每個資源,而不是刪除該資源組。If you created the resources for this article inside a resource group that contains other resources you want to keep, delete each resource individually from its respective pane instead of deleting the resource group.
登錄到 Azure 門戶,然后選擇“資源組”。Sign in to the Azure portal, and select Resource groups.
在“按名稱篩選”框中,輸入資源組的名稱。In the Filter by name box, enter the name of your resource group.
在結果列表中,選擇資源組名稱以查看概述。In the result list, select the resource group name to see an overview.
選擇“刪除資源組”。Select Delete resource group.
系統會要求確認是否刪除資源組。You're asked to confirm the deletion of the resource group. 重新鍵入資源組的名稱進行確認,然后選擇“刪除” 。Enter the name of your resource group to confirm, and select Delete.
片刻之后,將會刪除該資源組及其所有資源。After a few moments, the resource group and all its resources are deleted.
后續步驟Next steps
在本教程中,我們已創建一個引用 Key Vault 中存儲的值的應用程序配置密鑰。In this tutorial, you created an App Configuration key that references a value stored in Key Vault. 若要了解如何在 Java Spring 應用程序中使用功能標記,請繼續閱讀下一個教程。To learn how to use feature flags in your Java Spring application, continue to the next tutorial.
總結
以上是生活随笔為你收集整理的java获取keyvault_教程:在 Java Spring Boot 应用中使用 Azure 应用程序配置 Key Vault 引用 | Microsoft Docs...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS下创建配置RAID1
- 下一篇: CentOS7安装cuda及GPU驱动-