属性源

Vault 可以以多种不同的方式使用。一个特定的用例是使用 Vault 来存储加密的属性。Spring Vault 支持将 Vault 作为属性 source 使用 Spring 的 PropertySource 抽象获取配置属性。spring-doc.cadn.net.cn

您可以在其他特性源中引用存储在 Vault 中的特性,或者使用@Value(…).在引导需要数据存储在 Vault 内的 bean 时,需要特别注意。一个VaultPropertySource必须在此时初始化才能从 Vault 中检索属性。
Spring Boot/Spring Cloud 用户可以从 Spring Cloud Vault 的 配置集成,用于在应用程序启动期间初始化各种属性源。

注册VaultPropertySource

Spring Vault 提供了一个VaultPropertySource与 Vault 一起使用以获取 性能。它使用嵌套的data元素来公开存储的属性,并 在 Vault 中加密。spring-doc.cadn.net.cn

ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new VaultPropertySource(vaultTemplate, "secret/my-application"));

在上面的代码中,VaultPropertySource已添加为最高优先级 在搜索中。如果它包含 'foo' 属性,则将被检测并返回 领先于任何fooproperty 在任何其他PropertySource.MutablePropertySources公开了许多允许精确 作属性源集。spring-doc.cadn.net.cn

@VaultPropertySource

@VaultPropertySource注解提供了一个方便且声明性的 添加PropertySource到 Spring 的Environment@Configuration类。spring-doc.cadn.net.cn

@VaultPropertySource采用 Vault 路径,例如secret/my-application并将存储在节点中的数据公开在PropertySource.@VaultPropertySource支持与租约关联的密钥的租约 (即来自mysqlbackend) 和终端上的凭证轮换 租约到期。默认情况下,租约续订处于禁用状态。spring-doc.cadn.net.cn

示例 1.存储在 Vault 中的属性
{
  // …

  "data": {
    "database": {
      "password": ...
    },
    "user.name": ...,
  }

  // …
}
示例 2.声明@VaultPropertySource
@Configuration
@VaultPropertySource("secret/my-application")
public class AppConfig {

    @Autowired Environment env;

    @Bean
    public TestBean testBean() {
        TestBean testBean = new TestBean();
        testBean.setUser(env.getProperty("user.name"));
        testBean.setPassword(env.getProperty("database.password"));
        return testBean;
    }
}
例 3.声明@VaultPropertySource使用凭证轮换和前缀
@Configuration
@VaultPropertySource(value = "aws/creds/s3-access",
                     propertyNamePrefix = "aws.",
                     renewal = Renewal.ROTATE)
public class AppConfig {
  // provides aws.access_key and aws.secret_key properties
}
genericsecret 后端与 TTL (refresh_interval),而不是租约 ID 的PropertySource在达到其 TTL 时轮换通用密钥。
您可以使用@VaultPropertySource从受版本控制的 Key-Value 后端获取最新的密钥版本。确保不包含data/段。

任何${…​}placeholder 存在于@VaultPropertySourcepath 根据已针对环境注册的属性源集进行解析,如下例所示:spring-doc.cadn.net.cn

示例 4.声明@VaultPropertySource使用占位符的路径
@Configuration
@VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}",
                     propertyNamePrefix = "aws.",
                     renewal = Renewal.ROTATE)
public class AppConfig {
}

假设my.placeholder存在于已注册的属性源之一(例如,系统属性或环境变量)中,则占位符将解析为相应的值。 如果不是,则fallback/value用作默认值。 如果未指定 default 且无法解析属性,则IllegalArgumentException被抛出。spring-doc.cadn.net.cn

在某些情况下,严格控制可能是不可能的或不切实际的 使用@VaultPropertySource附注。 例如,如果@Configuration以上类是通过 component-scanning 中,顺序很难预测。 在这种情况下 - 如果覆盖很重要 - 建议将 用户回退到使用编程式 PropertySource API。 看ConfigurableEnvironmentMutablePropertySources了解详情。spring-doc.cadn.net.cn