使用 KMS 提供的秘密增强 DataSourceProperties 配置 bean

Enhance DataSourceProperties configuration bean with KMS provided secret

我想以编程方式设置数据源的密码,并且仍然使用 Spring GCP 和 Spring 数据的自动配置。

背景

我想获取我的加密 blob 密码并通过 Google KMS 解密。我读到 spring gcp 自动配置改变 DataSourceProperties bean 以应用 gcp 特定配置 (https://docs.spring.io/spring-cloud-gcp/docs/1.0.0.RELEASE/reference/html/_spring_jdbc.html#_literal_datasource_literal_creation_flow)。

现在我想再次改变 GcpCloudSqlAutoConfiguration 公开的 DataSourceProperties Bean。 如下公开 DataSourceProperties 不起作用,因为 GcpCloudSqlAutoConfiguration 不知道要使用哪个 Bean:由 spring 引导自动配置配置的那个还是我的。但是我的应该是在配置的最后一步应用的。

@Bean
public DataSourceProperties dataSourceProperties(DataSourceProperties dataSourceProperties) {
    dataSourceProperties.setPassword(getDecryptedSecret());
    return dataSourceProperties;
}

private String getDecryptedSecret() {
    // get encrypted password and decrypt it
    return "myDecryptedPassword"
}

Cloud KMS 提供使用对称密钥[1]的加密和解密数据and/or非对称密钥[2]。

您可以查看 DataSourceProperties[3],了解 Spring Boot 的更多支持选项。

[1]-https://cloud.google.com/kms/docs/encrypt-decrypt

[2]-https://cloud.google.com/kms/docs/encrypt-decrypt-rsa

[3]-https://github.com/spring-projects/spring-boot/blob/v2.1.8.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceProperties.java

您应该能够提供自己的 bootstrap 属性 源,其中包含 spring.datasource.password 的值。

参见:https://cloud.spring.io/spring-cloud-commons/multi/multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-property-sources

完整答案在项目 GitHub 中:https://github.com/spring-cloud/spring-cloud-gcp/issues/2330