教程:在 Java Spring 应用中使用 Key Vault 引用Tutorial: Use Key Vault references in a Java Spring app

本教程介绍如何将 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. 请先完成使用应用程序配置创建 Java Spring 应用,然后再继续。Before you continue, complete Create a Java Spring app with App Configuration first.

你可以使用任何代码编辑器执行本教程中的步骤。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

创建保管库Create a vault

  1. 选择 Azure 门户左上角的“创建资源”选项: Select the Create a resource option in the upper-left corner of the Azure portal:

    Key Vault 创建完成后的输出

  2. 在搜索框中输入 Key VaultIn the search box, enter Key Vault.

  3. 在结果列表中,选择左侧的“Key Vault” 。From the results list, select Key vaults on the left.

  4. 在“Key Vault”中选择“添加”。 In Key vaults, select Add.

  5. 在“创建 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-vault2For this tutorial, enter Contoso-vault2.
    • 在“区域”下拉列表中,选择一个位置。 In the Region drop-down list, choose a location.
  6. 将“创建 Key Vault”的其他选项保留默认值。 Leave the other Create key vault options with their default values.

  7. 选择“创建” 。Select Create.

目前,只有你的 Azure 帐户有权访问这个新保管库。At this point, your Azure account is the only one authorized to access this new vault.

Key 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.

  1. 在 Key Vault 属性页中选择“机密” 。From the Key Vault properties pages, select Secrets.
  2. 选择“生成/导入”。 Select Generate/Import.
  3. 在“创建机密”窗格中输入以下值: In the Create a secret pane, enter the following values:
    • 上传选项:输入 ManualUpload options: Enter Manual.
    • Name:输入 MessageName: Enter Message.
    • :输入 Hello from Key VaultValue: Enter Hello from Key Vault.
  4. 将“创建机密”的其他属性保留默认值。 Leave the other Create a secret properties with their default values.
  5. 选择“创建” 。Select Create.

将 Key Vault 引用添加到应用程序配置Add a Key Vault reference to App Configuration

  1. 登录 Azure 门户Sign in to the Azure portal. 选择“所有资源”,然后选择在快速入门中创建的应用程序配置存储实例 。Select All resources, and then select the App Configuration store instance that you created in the quickstart.

  2. 选择“配置资源管理器”。 Select Configuration Explorer.

  3. 选择“+ 创建” > “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

  1. 在本教程中,我们将使用一个服务主体向 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.partner.microsoftonline.cn",
    "resourceManagerEndpointUrl": "https://management.chinacloudapi.cn/",
    "sqlManagementEndpointUrl": "https://management.core.chinacloudapi.cn:8443/",
    "galleryEndpointUrl": "https://gallery.chinacloudapi.cn/",
    "managementEndpointUrl": "https://management.core.chinacloudapi.cn/"
    }
    
  2. 运行以下命令,使服务主体能够访问 Key Vault:Run the following command to let the service principal access your key vault:

    az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --secret-permissions delete get
    
  3. 运行以下命令获取 object-id,然后将其添加到应用配置。Run the following command to get your object-id, then add it to App Configuration.

    az ad sp show --id <clientId-of-your-service-principal>
    az role assignment create --role "App Configuration Data Reader" --assignee-object-id <objectId-of-your-service-principal> --resource-group <your-resource-group>
    
  4. 创建环境变量 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

  1. 创建一个名为“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.

  2. 打开“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}
    
  3. 打开 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;
    }
    
  4. 打开 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();
    }
    
  5. 创建一个名为 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();
        }
    
    }
    
  6. 创建一个名为 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();
        }
    }
    
  7. 在资源 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
    
  8. 使用 Maven 生成 Spring Boot 应用程序,然后运行该程序,例如:Build your Spring Boot application with Maven and run it, for example:

    mvn clean package
    mvn spring-boot:run
    
  9. 应用程序运行以后,请使用 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.

  1. 登录到 Azure 门户,然后选择“资源组”。Sign in to the Azure portal, and select Resource groups.
  2. 在“按名称筛选”框中,输入资源组的名称。In the Filter by name box, enter the name of your resource group.
  3. 在结果列表中,选择资源组名称以查看概述。In the result list, select the resource group name to see an overview.
  4. 选择“删除资源组”。Select Delete resource group.
  5. 系统会要求确认是否删除资源组。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.