使用 Spring Cloud Azure 自动装配 KeyClient

问题描述 投票:0回答:1

我已经设置了一个 Spring Cloud Azure 应用程序。我在我的 Azure Keyvault 中使用机密和密钥。我从集成 Secrets 开始,然后遵循 https://spring.io/projects/spring-cloud-azure,这允许我在应用程序配置属性 yaml 中仅使用以下内容来自动装配 Secret Client

spring:
  cloud:
    azure:
      keyvault:
        secret:
          endpoint:

我已经设置完毕并且工作非常顺利。

然后我转向 KeyClient,认为我可以重用其中的一些设置,但即使在源代码中

我也找不到类似的东西

这是否意味着我仍然必须包含所有其他配置道具,例如客户端 ID、客户端密钥等?看来我最终将不得不实现“不使用 Spring Cloud Azure”下的所有内容以及“使用 Spring Cloud Azure”下的所有内容,而我只能执行前者,而这对于 KeyClient 来说是必需的。如果我错了,请纠正我。谢谢!

spring azure azure-keyvault spring-cloud-azure
1个回答
0
投票

我尝试使用以下 Spring Boot 代码使用 KeyClient 从 Azure Key Vault 检索密钥。

代码:

KeyVaultKey服务:

import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.keys.KeyClient;
import com.azure.security.keyvault.keys.KeyClientBuilder;
import com.azure.security.keyvault.keys.models.JsonWebKey;
import com.azure.security.keyvault.keys.models.KeyVaultKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class KeyVaultKeyServices {

    @Value("${azure.keyvault.uri}")
    private String keyVaultUri;

    @Value("${azure.keyvault.key.name}")
    private String keyName;

    public String getKey() {
        DefaultAzureCredentialBuilder credentialBuilder = new DefaultAzureCredentialBuilder();
        KeyClient keyClient = new KeyClientBuilder()
                .vaultUrl(keyVaultUri)
                .credential(credentialBuilder.build())
                .buildClient();

        try {
            KeyVaultKey keyVaultKey = keyClient.getKey(keyName);
            JsonWebKey jsonWebKey = keyVaultKey.getKey();

            return jsonWebKey.toString();
        } catch (Exception e) {
            return "Error retrieving key: " + e.getMessage();
        }
    }
}

按键控制器:

import com.example.demo.service.KeyVaultKeyServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class KeyController {

    private final KeyVaultKeyServices keyVaultKeyServices;

    @Autowired
    public KeyController(KeyVaultKeyServices keyVaultKeyServices) {
        this.keyVaultKeyServices = keyVaultKeyServices;
    }

    @GetMapping("/key")
    public String getKey() {
        return keyVaultKeyServices.getKey();
    }
}

application.yml:

azure:
  keyvault:
    uri: https://<keyvault_name>.vault.azure.net/
    key:
      name: <key_name>

我授予了从 Azure Key Vault 读取密钥所需的权限,如下所示:

enter image description here

输出:

Spring Boot项目运行成功,如下图:

enter image description here

我在浏览器中从 Azure Key Vault 检索了密钥,如下所示。

http://localhost:8080/api/key

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.