4. 响应式CredHub操作介绍
接口 org.springframework.credhub.core.ReactiveCredHubOperations 和实现 org.springframework.credhub.core.ReactiveCredHubTemplate 是 Spring CredHub 响应式支持的核心类。
ReactiveCredHubOperations 提供对额外操作接口的访问,这些接口建模完整的 CredHub API:
/**
* Get the operations for saving, retrieving, and deleting credentials.
*/
ReactiveCredHubCredentialOperations credentials();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*/
ReactiveCredHubPermissionOperations permissions();
/**
* Get the operations for adding, retrieving, and deleting credential permissions.
*/
ReactiveCredHubPermissionV2Operations permissionsV2();
/**
* Get the operations for retrieving, regenerating, and updating certificates.
*/
ReactiveCredHubCertificateOperations certificates();
/**
* Get the operations for interpolating service binding credentials.
*/
ReactiveCredHubInterpolationOperations interpolation();
/**
* Get the operations for retrieving CredHub server information.
*/
ReactiveCredHubInfoOperations info();
4.1. 映射到 CredHub API
每个 0 接口的方法都直接映射到 CredHub HTTP API 的一个端点。
以下表格展示了 CredHub API 与适当的 Spring CredHub Reactive…Operations 接口之间的映射关系。
凭证Hub 权限 API (v1) |
|
凭证Hub 权限 API (v2) |
|
4.2. ReactiveCredHubOperations 自动配置
当应用程序属性配置得当且类路径上存在 Spring WebFlux 库时,一个 ReactiveCredHubOperations 的 Spring bean 会通过 Spring Boot 自配置创建。应用类可以自动装配该 bean 的一个实例以与 CredHub 服务器交互。
/*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.credhub;
@Component
public class ReactiveCredHubService {
private final ReactiveCredHubOperations credHubOperations;
private final SimpleCredentialName credentialName;
public ReactiveCredHubService(ReactiveCredHubOperations credHubOperations) {
this.credHubOperations = credHubOperations;
this.credentialName = new SimpleCredentialName("example", "password");
}
public Mono<String> generatePassword() {
PasswordParameters parameters = PasswordParameters.builder()
.length(12)
.excludeLower(false)
.excludeUpper(false)
.excludeNumber(false)
.includeSpecial(true)
.build();
return this.credHubOperations.credentials()
.generate(PasswordParametersRequest.builder().name(this.credentialName).parameters(parameters).build(),
PasswordCredential.class)
.map((password) -> password.getValue().getPassword());
}
public Mono<String> getPassword() {
return this.credHubOperations.credentials()
.getByName(this.credentialName, PasswordCredential.class)
.map((password) -> password.getValue().getPassword());
}
}