Introduction to VaultTemplate
位于 org.springframework.vault.core
包中的 VaultTemplate
类是 Spring Vault 支持的中心类,它提供了一套丰富的功能与 Vault 进行交互。模板提供了在 Vault 中读写和删除数据的便捷操作,并在您的域对象和 Vault 数据之间提供映射。
The class VaultTemplate
, located in the package org.springframework.vault.core
,
is the central class of the Spring’s Vault support providing a rich feature set to
interact with Vault. The template offers convenience operations to read, write and
delete data in Vault and provides a mapping between your domain objects and Vault data.
配置后, |
Once configured, |
Vault 文档和域类之间的映射是通过委托给 RestTemplate
完成的。Spring Web 支持提供映射基础设施。
The mapping between Vault documents and domain classes is done by delegating to
RestTemplate
. Spring Web support provides the mapping infrastructure.
VaultTemplate
类实现了 VaultOperations
接口。在尽可能多的情况下,VaultOperations
上的方法是以 Vault API 上可用的方法命名的,以使 API 对习惯使用 API 和 CLI 的现有 Vault 开发人员来说变得熟悉。例如,您会找到诸如“write”、“delete”、“read”和“revoke”这样的方法。设计目标是尽可能简化在 Vault API 和 VaultOperations
之间进行转换。这两个 API 之间的主要区别在于 VaultOperations
可以传递域对象,而不是 JSON 键值对。
The VaultTemplate
class implements the interface VaultOperations
.
In as much as possible, the methods on VaultOperations
are named after methods
available on the Vault API to make the API familiar to existing Vault developers
who are used to the API and CLI. For example, you will find methods such as
"write", "delete", "read", and "revoke".
The design goal was to make it as easy as possible to transition between
the use of the Vault API and VaultOperations
. A major difference in between
the two APIs is that VaultOperations
can be passed domain objects instead of
JSON Key-Value pairs.
引用 |
The preferred way to reference the operations on |
虽然 VaultTemplate
上有很多便利方法可以帮助您轻松执行常见任务,但如果您需要直接访问 Vault API 来访问未 VaultTemplate
明确公开的功能,则可以使用多种执行回调方法来访问底层 API。执行回调将为您提供 RestOperations
对象的引用。有关更多信息,请参见 Execution Callbacks 部分。
While there are many convenience methods on VaultTemplate
to help you easily
perform common tasks if you should need to access the Vault API directly to access
functionality not explicitly exposed by the VaultTemplate
you can use one of
several execute callback methods to access underlying APIs. The execute callbacks
will give you a reference to a RestOperations
object.
Please see the section vault.core.executioncallback for more information.
现在,让我们来看一个示例,了解如何在 Spring 容器的上下文中使用 Vault。
Now let’s look at a examples of how to work with Vault in the context of the Spring container.
Registering and configuring Spring Vault beans
使用 Spring Vault 不需要 Spring 上下文。但是,在受管上下文中注册的 VaultTemplate
和 SessionManager
的实例将参与 Spring IoC 容器提供的 {spring-framework-docs}core.html#beans-factory-nature[生命周期事件] 。这有助于在应用程序关闭时释放活动 Vault 会话。您还可以受益于在整个应用程序中重复使用相同的 VaultTemplate
实例。
Using Spring Vault does not require a Spring Context. However, instances of VaultTemplate
and SessionManager
registered inside a managed context will participate
in {spring-framework-docs}core.html#beans-factory-nature[lifecycle events]
provided by the Spring IoC container. This is useful to dispose active Vault sessions upon
application shutdown. You also benefit from reusing the same VaultTemplate
instance across your application.
Spring Vault 带有一个支持配置类,该类提供了在 Spring 上下文中使用的 bean 定义。应用程序配置类通常从 AbstractVaultConfiguration
扩展,并且需要提供特定于环境的附加详细信息。
Spring Vault comes with a supporting configuration class that provides bean definitions
for use inside a Spring context. Application configuration
classes typically extend from AbstractVaultConfiguration
and are required to
provide additional details that are environment specific.
从 AbstractVaultConfiguration
扩展需要实现` VaultEndpoint vaultEndpoint()` 和 ClientAuthentication clientAuthentication()
方法。
Extending from AbstractVaultConfiguration
requires to implement
` VaultEndpoint vaultEndpoint()` and ClientAuthentication clientAuthentication()
methods.
@Configuration
public class AppConfig extends AbstractVaultConfiguration {
/**
* Specify an endpoint for connecting to Vault.
*/
@Override
public VaultEndpoint vaultEndpoint() {
return new VaultEndpoint(); 1
}
/**
* Configure a client authentication.
* Please consider a more secure authentication method
* for production use.
*/
@Override
public ClientAuthentication clientAuthentication() {
return new TokenAuthentication("…"); 2
}
}
1 | Create a new VaultEndpoint that points by default to https://localhost:8200 . |
2 | This sample uses TokenAuthentication to get started quickly.
See [vault.core.authentication] for details on supported authentication methods. |
@Configuration
public class AppConfig extends AbstractVaultConfiguration {
@Value("${vault.uri}")
URI vaultUri;
/**
* Specify an endpoint that was injected as URI.
*/
@Override
public VaultEndpoint vaultEndpoint() {
return VaultEndpoint.from(vaultUri); 1
}
/**
* Configure a Client Certificate authentication.
* {@link RestOperations} can be obtained from {@link #restOperations()}.
*/
@Override
public ClientAuthentication clientAuthentication() {
return new ClientCertificateAuthentication(restOperations()); 2
}
}
1 | VaultEndpoint can be constructed using various factory methods such as
from(URI uri) or VaultEndpoint.create(String host, int port) . |
2 | Dependencies for ClientAuthentication methods can be obtained either from
AbstractVaultConfiguration or provided by your configuration. |
在某些情况下,创建自定义配置类可能很麻烦。了解 |
Creating a custom configuration class might be cumbersome in some cases.
Take a look at |
Session Management
Spring Vault 需要 ClientAuthentication
登录并访问 Vault。有关认证的详细信息,请参见 [vault.core.authentication]。Vault 登录不应在每次经过认证的 Vault 交互中进行,而必须在整个会话中重用。这个方面由 SessionManager
实现处理。一个 SessionManager
决定多久获取令牌一次,以及撤销和续订。Spring Vault 提供了两种实现:
Spring Vault requires a ClientAuthentication
to login and access Vault.
See [vault.core.authentication] on details regarding authentication.
Vault login should not occur on each authenticated Vault interaction but
must be reused throughout a session. This aspect is handled by a
SessionManager
implementation. A SessionManager
decides how often it
obtains a token, about revocation and renewal. Spring Vault comes with two implementations:
-
SimpleSessionManager
: Just obtains tokens from the suppliedClientAuthentication
without refresh and revocation -
LifecycleAwareSessionManager
: ThisSessionManager
schedules token renewal if a token is renewable and revoke a login token on disposal. Renewal is scheduled with anAsyncTaskExecutor
.LifecycleAwareSessionManager
is configured by default if usingAbstractVaultConfiguration
.
Using EnvironmentVaultConfiguration
Spring Vault 包含 EnvironmentVaultConfiguration
配置来自 Spring Environment
的 Vault 客户端,以及一组预定义属性键。EnvironmentVaultConfiguration
支持经常应用的配置。通过从最合适的配置类派生可支持其他配置。将 EnvironmentVaultConfiguration
与 @Import(EnvironmentVaultConfiguration.class)
一起包含到现有的基于 Java 的配置类中,并通过 Spring 的任何 PropertySource
提供配置属性。
Spring Vault includes EnvironmentVaultConfiguration
configure the Vault client from Spring’s Environment
and a set of predefined
property keys. EnvironmentVaultConfiguration
supports frequently applied configurations. Other configurations are supported by deriving from the most appropriate configuration class. Include EnvironmentVaultConfiguration
with @Import(EnvironmentVaultConfiguration.class)
to existing
Java-based configuration classes and supply configuration properties through any of Spring’s `PropertySource`s.
@PropertySource("vault.properties")
@Import(EnvironmentVaultConfiguration.class)
public class MyConfiguration{
}
vault.uri=https://localhost:8200
vault.token=00000000-0000-0000-0000-000000000000
Property keys
-
Vault URI:
vault.uri
-
SSL Configuration
-
Keystore resource:
vault.ssl.key-store
(optional) -
Keystore password:
vault.ssl.key-store-password
(optional) -
Keystore type:
vault.ssl.key-store-type
(optional, typicallyjks
, supports alsopem
) -
Truststore resource:
vault.ssl.trust-store
(optional) -
Truststore password:
vault.ssl.trust-store-password
(optional) -
Truststore type:
vault.ssl.trust-store-type
(optional, typicallyjks
, supports alsopem
) -
Enabled SSL/TLS protocols:
vault.ssl.enabled-protocols
(since 2.3.2, optional, protocols separated with comma) -
Enabled SSL/TLS cipher suites:
vault.ssl.enabled-cipher-suites
(since 2.3.2, optional, cipher suites separated with comma)
-
-
Authentication method:
vault.authentication
(defaults toTOKEN
, supported authentication methods are:TOKEN
,APPID
,APPROLE
,AWS_EC2
,AWS_IAM
,AZURE
,CERT
,CUBBYHOLE
,KUBERNETES
)
Authentication-specific property keys
-
Vault Token:
vault.token
-
AppId path:
vault.app-id.app-id-path
(defaults toapp-id
) -
AppId:
vault.app-id.app-id
-
UserId:
vault.app-id.user-id
.MAC_ADDRESS
andIP_ADDRESS
useMacAddressUserId
, respectiveIpAddressUserId
user id mechanisms. Any other value is used withStaticUserId
.
-
AppRole path:
vault.app-role.app-role-path
(defaults toapprole
) -
RoleId:
vault.app-role.role-id
-
SecretId:
vault.app-role.secret-id
(optional)
-
AWS EC2 path:
vault.aws-ec2.aws-ec2-path
(defaults toaws-ec2
) -
Role:
vault.aws-ec2.role
-
RoleId:
vault.aws-ec2.role-id
(deprecated: usevault.aws-ec2.role
instead) -
Identity Document URL:
vault.aws-ec2.identity-document
(defaults tohttp://169.254.169.254/latest/dynamic/instance-identity/pkcs7
)
-
Role:
vault.aws-iam.role
-
Azure MSI path:
vault.azure-msi.azure-path
(defaults toazure
) -
Role:
vault.azure-msi.role
-
Metadata Service URL:
vault.azure-msi.metadata-service
(defaults tohttp://169.254.169.254/metadata/instance?api-version=2017-08-01
) -
Identity TokenService URL:
vault.azure-msi.identity-token-service
(defaults tohttp://169.254.169.254/metadata/identity/oauth2/token?resource=https://vault.hashicorp.com&api-version=2018-02-01
)
没有配置选项。
No configuration options.
-
Initial Vault Token:
vault.token
-
Kubernetes path:
vault.kubernetes.kubernetes-path
(defaults tokubernetes
) -
Role:
vault.kubernetes.role
-
Path to service account token file:
vault.kubernetes.service-account-token-file
(defaults to/var/run/secrets/kubernetes.io/serviceaccount/token
)
Execution callbacks
所有 Spring 模板类的常见设计特点就是所有功能都发送至其中一个模板执行回调方法。这样有助于确保以一致的方式执行异常以及可能所需的任何资源管理。虽然这在 JDBC 和 JMS 的情况下比在 Vault 的情况下需要更多,但它仍然为访问和记录提供一个地点。因此,使用 execute 回调是访问 Vault API 的首选方法,以便执行我们未在 VaultTemplate
上公开为方法的不常见操作。
One common design feature of all Spring template classes is that all functionality is routed into one of the templates execute callback methods.
This helps ensure that exceptions and any resource management that maybe required are performed consistency.
While this was of much greater need in the case of JDBC and JMS than with Vault, it still offers a single spot for access and logging to occur.
As such, using the execute callback is the preferred way to access the Vault API
to perform uncommon operations that we’ve not exposed as methods on VaultTemplate
.
这里列出了一些 execute 回调方法。
Here is a list of execute callback methods.
-
<T> T
doWithVault(RestOperationsCallback<T> callback)
Executes the givenRestOperationsCallback
, allows to interact with Vault usingRestOperations
without requiring a session. -
<T> T
doWithSession(RestOperationsCallback<T> callback)
Executes the givenRestOperationsCallback
, allows to interact with Vault in an authenticated session.
以下是一个使用 ClientCallback
初始化 Vault 的示例:
Here is an example that uses the ClientCallback
to initialize Vault:
vaultOperations.doWithVault(new RestOperationsCallback<VaultInitializationResponse>() {
@Override
public VaultInitializationResponse doWithRestOperations(RestOperations restOperations) {
ResponseEntity<VaultInitializationResponse> exchange = restOperations
.exchange("/sys/init", HttpMethod.PUT,
new HttpEntity<Object>(request),
VaultInitializationResponse.class);
return exchange.getBody();
}
});