我正在尝试设置一个 Spring boot 应用程序来连接到 Azure keyvault 并获取机密。 我查看了各种代码示例,但无法让一个工作。
没有与 keyvault 库本身相关的错误,但是 Spring bean 没有使用从秘密中获取的属性进行初始化。
我正在使用 Spring boot 2.7.3,keyvault starter lib 是 4.2.0。这就是我提到的获取我的属性配置。 https://microsoft.github.io/spring-cloud-azure/4.2.0/reference/html/appendix.html#_azure_key_vault_secrets_properties
application.yml
------------
spring:
cloud:
azure:
keyvault:
secret:
enabled: true
endpoint: https://uri/
credential:
client-certificate-path: <path to pem file>
client-id: <client-id>
profile:
tenant-id: <tenant-id>
build.gradle
--------------
implementation 'com.azure.spring:spring-cloud-azure-starter-keyvault-secrets:4.2.0'
Spring bean
-------------
@Configuration
@Getter
@Setter
public class AKVProperties {
@Value("${MYAPP-DB-LOGIN-PASSWORD}")
private String dbPassword1;
...
Exception at startup:
----------------------
Error creating bean with name 'AKVProperties': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'MYAPP-DB-LOGIN-PASSWORD' in value "${MYAPP-DB-LOGIN-PASSWORD}"
我认为问题出在
application.yaml
文件上。你必须在property-sources:
.下设置你的配置设置
这是
application.yaml
我在property-sources:
下设置everython的地方
spring:
cloud:
azure:
keyvault:
secret:
property-sources:
- credential:
client-id: <CLIENT ID>
client-secret: <CLIENT SECRET>
endpoint: '<END POINT>'
profile:
tenant-id: <TENANT ID>
@Value("${secret}")
private String secret;
然后我只是控制台记录它们。
输出:
密钥库:
我的回答侧重于较新的版本,因此从 4.3.0 版开始,它将起作用。
参考链接您可能需要的其他属性。
注意:您至少需要 SPRING 3.X.X 和 JAVA >=16
您的 application.properties 如下所示。
spring.cloud.azure.keyvault.secret.property-source-enabled=true
spring.cloud.azure.keyvault.secret.property-sources[0].endpoint=
spring.cloud.azure.keyvault.secret.property-sources[0].profile.tenant-id=
spring.cloud.azure.keyvault.secret.property-sources[0].credential.client-id=
spring.cloud.azure.keyvault.secret.property-sources[0].credential.client-secret
您的 pom.xml 文件应包含以下依赖项
<dependencies>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-keyvault-secrets</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-dependencies</artifactId>
<version>5.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
现在,您应该能够在您的属性和 yaml 文件中使用 Azure Key Vault 机密。例如:
spring.security.user.password=${your-vault-key}
此外,它们也可以通过使用
导入到代码中@Value("${database.secret.value}")
private String mySecret;
这里 your-vault-key 和 database.secret.value 只是举例,您将使用您在 Azure 上创建的保管库密钥名称。
如果有人需要 Azure 方面的实施步骤,请告诉我,我会更新我的答案。