© 2017-2021 The original authors.

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Spring CredHub provides client-side support for storing, retrieving, and deleting credentials from a CredHub server running in a Cloud Foundry platform.

CredHub provides an HTTP API to securely store, generate, retrieve, and delete credentials of various types. Spring CredHub provides a Java binding for the CredHub API, making it easy to integrate Spring applications with CredHub.

1. Getting started

Spring CredHub supports CredHub server version 1.x and 2.x. This library is intended to provide full coverage of the CredHub API - all operations on all credential types.

Spring CredHub has been optimized to work with Spring Boot applications. To include Spring CredHub in a Spring Boot application, add some dependencies to the project build file.

1.1. Maven Dependencies

Add the Spring CredHub starter to the dependencies section of the build file:

    <dependencies>
        <dependency>
            <groupId>org.springframework.credhub</groupId>
            <artifactId>spring-credhub-starter</artifactId>
            <version>2.3.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

To enable reactive support in Spring CredHub, add the following Spring WebFlux dependency to the build file:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>2.7.5</version>
        </dependency>
    </dependencies>

To use OAuth2 authentication to CredHub, add the following Spring Security dependencies to the build file:

    <dependencies>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
            <version>5.7.5</version>
        </dependency>
    </dependencies>

1.2. Gradle Dependencies

Add the Spring CredHub starter to the dependencies section of the build file:

    dependencies {
        compile('org.springframework.credhub:spring-credhub-starter:2.3.1-SNAPSHOT')
    }

To enable reactive support in Spring CredHub, add the following Spring WebFlux dependency to the build file:

    dependencies {
        compile("org.springframework.boot:spring-boot-starter-webflux:2.7.5")
    }

To use OAuth2 authentication to CredHub, add the following Spring Security dependencies to the build file:

    dependencies {
        compile("org.springframework.security:spring-security-config:5.7.5")
        compile("org.springframework.security:spring-security-oauth2-client:5.7.5")
    }

2. Spring Boot Configuration

When using the Spring CredHub starter dependency, Spring CredHub can be configured with Spring Boot application properties. With the proper configuration properties, Spring CredHub will auto-configure a connection to a CredHub server.

2.1. Mutual TLS Authentication

An application running on Cloud Foundry can authenticate to a CredHub server deployed to the same platform using mutual TLS. Mutual TLS is the default authentication scheme when no other authentication credentials are provided. To use mutual TLS authentication to a CredHub server, simply provide the URL of the CredHub server as an application property:

spring:
  credhub:
    url: [CredHub server URL]

See the CredHub documentation for more information on mutual TLS authentication.

An application running on Cloud Foundry can use the internal address https://credhub.service.cf.internal:8844 to communicate with a CredHub server deployed to the same platform.

2.2. OAuth2 Authentication

OAuth2 can be used to authenticate via UAA to any CredHub server. Spring CredHub supports client credentials grant tokens for authentication using the following Spring CredHub and Spring Security configuration:

spring:
  credhub:
    url: [CredHub server URL]
    oauth2:
      registration-id: credhub-client
  security:
    oauth2:
      client:
        registration:
          credhub-client:
            provider: uaa
            client-id: [OAuth2 client ID]
            client-secret: [OAuth2 client secret]
            authorization-grant-type: client_credentials
        provider:
          uaa:
            token-uri: [UAA token server endpoint]

The ID provided in spring.credhub.oauth2.registration-id must refer to a client configured under spring.security.oauth2.client.registration. See the Spring Boot documentation for more information on Spring Boot OAuth2 client configuration.

The OAuth2 client specified in the Spring Security client registration must have CredHub scopes such as credhub.read or credhub.write to perform most operations. See the CredHub documentation for more information on OAuth2 authentication with UAA.

2.2.1. Auto-configuration of Spring Security OAuth2

When spring.credhub.oauth2 properties are set and Spring Security is on the application classpath, Spring CredHub will auto-configure the Spring Security beans required for OAuth2 authentication. An application can provide the required Spring Security OAuth2 beans to override the auto-configuration if necessary.

Servlet and Non-reactive Applications

Spring CredHub requires beans of the following types, provided by Spring Security, in order to authenticate using OAuth2.

Required Bean Type Auto-configured Type

ClientRegistrationRepository

InMemoryClientRegistrationRepository

OAuth2AuthorizedClientRepository

AuthenticatedPrincipalOAuth2AuthorizedClientRepository

OAuth2AuthorizedClientManager

DefaultOAuth2AuthorizedClientManager

The auto-configured DefaultOAuth2AuthorizedClientManager assumes the application is running in a servlet container and has an active HttpServletRequest. An application might need to provide an alternate implementation of the OAuth2AuthorizedClientManager bean such as AuthorizedClientServiceOAuth2AuthorizedClientManager to process requests outside of an HttpServletRequest, as shown in the following example:

/*
 * 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;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;

@Configuration
public class CredHubSecurityConfiguration {

	@Bean
	public AuthorizedClientServiceOAuth2AuthorizedClientManager reactiveClientManager(
			ClientRegistrationRepository clientRegistrationRepository,
			OAuth2AuthorizedClientService authorizedClientService) {
		AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
				clientRegistrationRepository, authorizedClientService);
		clientManager.setAuthorizedClientProvider(new ClientCredentialsOAuth2AuthorizedClientProvider());
		return clientManager;
	}

}

Refer to the Spring Security documentation for more information and examples of configuring other beans.

Reactive Applications

Spring CredHub requires beans of the following types, provided by Spring Security, in order to authenticate using OAuth2.

Required Bean Type Auto-configured Type

ReactiveClientRegistrationRepository

InMemoryReactiveClientRegistrationRepository

ServerOAuth2AuthorizedClientRepository

UnAuthenticatedServerOAuth2AuthorizedClientRepository

ReactiveOAuth2AuthorizedClientManager

DefaultReactiveOAuth2AuthorizedClientManager

The auto-configured DefaultReactiveOAuth2AuthorizedClientManager requires an active ServerHttpRequest context. An application might need to provide an alternate implementation of the ReactiveOAuth2AuthorizedClientManager bean such as AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager to process requests outside of an ServerHttpRequest, as shown in the following example:

/*
 * 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;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ClientCredentialsReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;

@Configuration
public class CredHubReactiveSecurityConfiguration {

	@Bean
	public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager(
			ReactiveClientRegistrationRepository clientRegistrationRepository,
			ReactiveOAuth2AuthorizedClientService authorizedClientService) {
		AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
				clientRegistrationRepository, authorizedClientService);
		clientManager.setAuthorizedClientProvider(new ClientCredentialsReactiveOAuth2AuthorizedClientProvider());
		return clientManager;
	}

}

Refer to the Spring Security documentation for more information and examples of configuring other beans.

3. Introduction to CredHubOperations

The interface org.springframework.credhub.core.CredHubOperations and the implementation org.springframework.credhub.core.CredHubTemplate are the central classes in Spring CredHub. CredHubOperations provides access to additional operations interfaces that model the full CredHub API:

/**
 * Get the operations for saving, retrieving, and deleting credentials.
 */
CredHubCredentialOperations credentials();

/**
 * Get the operations for adding, retrieving, and deleting credential permissions.
 */
CredHubPermissionOperations permissions();

/**
 * Get the operations for adding, retrieving, and deleting credential permissions.
 */
CredHubPermissionV2Operations permissionsV2();

/**
 * Get the operations for retrieving, regenerating, and updating certificates.
 */
CredHubCertificateOperations certificates();

/**
 * Get the operations for interpolating service binding credentials.
 */
CredHubInterpolationOperations interpolation();

/**
 * Get the operations for retrieving CredHub server information.
 */
CredHubInfoOperations info();

3.1. Mapping to CredHub API

Each method of the Operations interfaces maps directly to one endpoint of the CredHub HTTP API. The following table shows the mapping between the CredHub API and the appropriate Spring CredHub Operations interface.

CredHub Credentials API

CredHubCredentialOperations

CredHub Permissions API (v1)

CredHubPermissionOperations

CredHub Permissions API (v2)

CredHubPermissionV2Operations

CredHub Certificates API

CredHubCertificateOperations

CredHub Interpolation API

CredHubInterpolationOperations

CredHub Information API

CredHubInfoOperations

3.2. CredHubOperations Auto-configuration

A CredHubOperations Spring bean is created using Spring Boot auto-configuration when application properties are properly configured. Application classes can autowire an instance of this bean to interact with a CredHub server.

/*
 * 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;

import org.springframework.credhub.core.CredHubOperations;
import org.springframework.credhub.support.CredentialDetails;
import org.springframework.credhub.support.SimpleCredentialName;
import org.springframework.credhub.support.password.PasswordCredential;
import org.springframework.credhub.support.password.PasswordParameters;
import org.springframework.credhub.support.password.PasswordParametersRequest;
import org.springframework.stereotype.Component;

@Component
public class CredHubService {

	private final CredHubOperations credHubOperations;

	private final SimpleCredentialName credentialName;

	public CredHubService(CredHubOperations credHubOperations) {
		this.credHubOperations = credHubOperations;

		this.credentialName = new SimpleCredentialName("example", "password");
	}

	public String generatePassword() {
		PasswordParameters parameters = PasswordParameters.builder().length(12).excludeLower(false).excludeUpper(false)
				.excludeNumber(false).includeSpecial(true).build();

		CredentialDetails<PasswordCredential> password = this.credHubOperations.credentials()
				.generate(PasswordParametersRequest.builder().name(this.credentialName).parameters(parameters).build());

		return password.getValue().getPassword();
	}

	public String getPassword() {
		CredentialDetails<PasswordCredential> password = this.credHubOperations.credentials()
				.getByName(this.credentialName, PasswordCredential.class);

		return password.getValue().getPassword();
	}

}

4. Introduction to ReactiveCredHubOperations

The interface org.springframework.credhub.core.ReactiveCredHubOperations and the implementation org.springframework.credhub.core.ReactiveCredHubTemplate are the central classes in Spring CredHub reactive support. ReactiveCredHubOperations provides access to additional operations interfaces that model the full 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. Mapping to CredHub API

Each method of the Reactive…​Operations interfaces maps directly to one endpoint of the CredHub HTTP API. The following table shows the mapping between the CredHub API and the appropriate Spring CredHub Reactive…​Operations interface.

CredHub Credentials API

ReactiveCredHubCredentialOperations

CredHub Permissions API (v1)

ReactiveCredHubPermissionOperations

CredHub Permissions API (v2)

ReactiveCredHubPermissionV2Operations

CredHub Certificates API

ReactiveCredHubCertificateOperations

CredHub Interpolation API

ReactiveCredHubInterpolationOperations

CredHub Information API

ReactiveCredHubInfoOperations

4.2. ReactiveCredHubOperations Auto-configuration

A ReactiveCredHubOperations Spring bean is created using Spring Boot auto-configuration when application properties are properly configured and the Spring WebFlux library is on the classpath. Application classes can autowire an instance of this bean to interact with a CredHub server.

/*
 * 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;

import reactor.core.publisher.Mono;

import org.springframework.credhub.core.ReactiveCredHubOperations;
import org.springframework.credhub.support.SimpleCredentialName;
import org.springframework.credhub.support.password.PasswordCredential;
import org.springframework.credhub.support.password.PasswordParameters;
import org.springframework.credhub.support.password.PasswordParametersRequest;
import org.springframework.stereotype.Component;

@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());
	}

}

5. HTTP Client Support

Spring CredHub CredHubOperations supports multiple HTTP client libraries to communicate with the CredHub API. The following libraries are supported:

Choosing a specific client library requires the appropriate dependency to be available on the application classpath. The application classpath will be inspected for each client library in the order listed above.

Spring CredHub ReactiveCredHubOperations only supports the Netty HTTP client library.

5.1. Apache HttpComponents

To use Apache HttpComponents to communicate with CredHub, add the following dependency to the application:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
</dependency>
Apache HttpClient’s wire logging can be enabled through logging configuration. Make sure to not accidentally enable wire logging as logs may expose traffic (including tokens and secrets) between your application and CredHub in plain text.

5.2. OkHttp 3

To use OkHttp 3 to communicate with CredHub, add the following dependency to the application:

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
</dependency>

5.3. Netty

To use Netty to communicate with CredHub, add the following dependency to the application:

<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
</dependency>