属性源

Vault 可以通过多种方式使用。其中一个特定的用例是使用 Vault 存储加密属性。Spring Vault 支持将 Vault 作为属性源,以使用 Spring 的 PropertySource 抽象获取配置属性。

您可以在其他属性源中引用 Vault 中存储的属性,或使用 @Value(…) 进行值注入。在引导需要 Vault 中存储的数据的 Bean 时需要特别注意。此时必须初始化 VaultPropertySource,才能从 Vault 中检索属性。
Spring Boot/Spring Cloud 用户可以从 Spring Cloud Vault 的配置集成中受益,该集成在应用程序启动期间初始化各种属性源。
Vault 通过 Vault 的 sys/internal/ui/mounts/… 端点确定挂载路径。请确保您的策略允许访问该路径,否则您将无法使用 Vault 属性源。

注册 VaultPropertySource

Spring Vault 提供了一个 VaultPropertySource,用于与 Vault 配合使用以获取属性。它使用嵌套的 data 元素来暴露存储在 Vault 中并加密的属性。

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

在上面的代码中,VaultPropertySource 以最高优先级添加到搜索中。如果它包含一个“foo”属性,它将被检测并优先于任何其他 PropertySource 中的任何“foo”属性返回。MutablePropertySources 暴露了许多方法,允许精确操作属性源集合。

@VaultPropertySource

@VaultPropertySource 注解提供了一种方便的声明式机制,可以将 PropertySource 添加到 Spring 的 Environment 中,以与 @Configuration 类一起使用。

@VaultPropertySource 接受一个 Vault 路径,例如 secret/my-application,并将该节点中存储的数据公开为 PropertySource@VaultPropertySource 支持与租约关联的密钥(即来自 mysql 后端的凭证)的租约续期,以及在租约到期时的凭证轮换。默认情况下禁用租约续期。

示例 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
}
generic 秘密后端获取的秘密与 TTL (refresh_interval) 相关联,但没有租约 ID。Spring Vault 的 PropertySource 在达到其 TTL 时轮换通用秘密。
您可以使用 @VaultPropertySource 从版本化键值后端获取最新版本的秘密。请确保路径中不包含 data/ 段。

@VaultPropertySource 路径中存在的任何 ${…} 占位符都将根据环境中已注册的属性源集进行解析,如下例所示

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

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

在某些情况下,当使用 @VaultPropertySource 注解时,可能无法或不切实际地严格控制属性源的顺序。例如,如果上述 @Configuration 类通过组件扫描注册,则顺序难以预测。在这种情况下——如果覆盖很重要——建议用户回退到使用编程的 PropertySource API。有关详细信息,请参阅 ConfigurableEnvironmentMutablePropertySources

© . This site is unofficial and not affiliated with VMware.