屬性源

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.