Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/modules/ROOT/pages/client.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,27 @@ spring:

The `spring.cloud.config.password` and `spring.cloud.config.username` values override anything that is provided in the URI.

If you use OAuth2 security on the server, clients need to know the client ID and client secret.
You can specify the client ID and client secret via separate properties, as shown in the following example:

[source,yaml]
----

spring:
cloud:
config:
uri: https://myconfig.mycompany.com
oauth2:
enabled: true
provider:
token-uri: https://auth.acme.com/oauth/token
registration:
client-id: client-id
client-secret: client-secret
authorization-grant-type: client_credentials

----

If you deploy your apps on Cloud Foundry, the best way to provide the password is through service credentials (such as in the URI, since it does not need to be in a config file).
The following example works locally and for a user-provided service on Cloud Foundry named `configserver`:

Expand Down
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
<module>spring-cloud-config-sample</module>
<module>spring-cloud-starter-config</module>
<module>spring-cloud-config-client-tls-tests</module>
<module>spring-cloud-config-client-oauth2-tests</module>
<module>docs</module>
</modules>
<dependencyManagement>
Expand Down Expand Up @@ -178,6 +179,7 @@
<configuration>
<excludeArtifacts>
<artifact>spring-cloud-config-client-tls-tests</artifact>
<artifact>spring-cloud-config-client-oauth2-tests</artifact>
<artifact>spring-cloud-config-sample</artifact>
</excludeArtifacts>
</configuration>
Expand Down
103 changes: 103 additions & 0 deletions spring-cloud-config-client-oauth2-tests/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-config-client-oauth2-tests</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Config Client OAuth2 Tests</name>

<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>

<url>https://spring.io</url>
<description>Spring Cloud Config Client OAuth2 Integration Tests</description>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>

<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dasniko</groupId>
<artifactId>testcontainers-keycloak</artifactId>
<version>3.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.20.0</version>
</dependency>
<!-- MockServer for simulating a protected resource server -->
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>5.15.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-client-java</artifactId>
<version>5.15.0</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<!--skip deploy (this is just a test module) -->
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
* Copyright 2013-present 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 org.springframework.cloud.config.client;

import java.net.URI;

import dasniko.testcontainers.keycloak.KeycloakContainer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.MediaType;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

/**
* IntegrationTest for OAuth2 support in ConfigClientRequestTemplateFactory using Keycloak
* Test container as the Authorization Server and MockServer as a protected resource
* server.
*/
@Tag("DockerRequired")
@Testcontainers
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ConfigClientRequestTemplateFactoryOAuth2Tests {

private static final Log log = LogFactory.getLog(ConfigClientRequestTemplateFactoryOAuth2Tests.class);

@Container
static KeycloakContainer keycloak = new KeycloakContainer().withRealmImportFile("test-realm.json"); // classpath
// resource

private ClientAndServer mockServer;

private MockServerClient mockClient;

@BeforeAll
void startMockServer() {
mockServer = ClientAndServer.startClientAndServer(0);
mockClient = new MockServerClient("localhost", mockServer.getLocalPort());
}

@BeforeEach
void resetExpectations() {
mockClient.clear(request().withPath("/secure"));
mockClient.when(request().withMethod("GET").withPath("/secure")).respond(request -> {
if (request.containsHeader("Authorization")) {
String authHeader = request.getFirstHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
return response().withStatusCode(200).withContentType(MediaType.TEXT_PLAIN).withBody("ok");
}
}
return response().withStatusCode(401);
});
}

@AfterAll
void tearDown() {
if (mockClient != null) {
mockClient.close();
}
if (mockServer != null) {
mockServer.stop();
}
}

@Test
void restTemplateAddsBearerTokenFromKeycloakUsingClientCredentials() {
// given OAuth2 client configuration pointing to Keycloak token endpoint
String tokenUri = keycloak.getAuthServerUrl() + "/realms/test-realm/protocol/openid-connect/token";

ConfigClientProperties props = new ConfigClientProperties();
props.getOauth2().setEnabled(true);

OAuth2ClientProperties.Provider provider = props.getOauth2().getProvider();
provider.setTokenUri(tokenUri);

OAuth2ClientProperties.Registration registration = props.getOauth2().getRegistration();
registration.setClientId("config-client");
registration.setClientSecret("my-client-secret");
registration.setAuthorizationGrantType("client_credentials");

ConfigClientRequestTemplateFactory factory = new ConfigClientRequestTemplateFactory(log, props);
RestTemplate restTemplate = factory.create();

// when
String url = "http://localhost:" + mockServer.getLocalPort() + "/secure";
ResponseEntity<String> response = restTemplate.getForEntity(URI.create(url), String.class);

// then
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
assertThat(response.getBody()).isEqualTo("ok");

HttpRequest[] recorded = mockClient.retrieveRecordedRequests(request().withPath("/secure"));
assertThat(recorded).hasSize(1);
String authHeader = recorded[0].getFirstHeader("Authorization");
assertThat(authHeader).isNotNull().startsWith("Bearer ");
}

@Test
void restTemplateAddsBearerTokenFromKeycloakUsingClientCredentialsAndIssuerUri() {
// given OAuth2 client configuration pointing to Keycloak issuer endpoint
String issuerUri = keycloak.getAuthServerUrl() + "/realms/test-realm";

ConfigClientProperties props = new ConfigClientProperties();
props.getOauth2().setEnabled(true);

OAuth2ClientProperties.Provider provider = props.getOauth2().getProvider();
provider.setIssuerUri(issuerUri);

OAuth2ClientProperties.Registration registration = props.getOauth2().getRegistration();
registration.setClientId("config-client");
registration.setClientSecret("my-client-secret");
registration.setAuthorizationGrantType("client_credentials");

ConfigClientRequestTemplateFactory factory = new ConfigClientRequestTemplateFactory(log, props);
RestTemplate restTemplate = factory.create();

// when
String url = "http://localhost:" + mockServer.getLocalPort() + "/secure";
ResponseEntity<String> response = restTemplate.getForEntity(URI.create(url), String.class);

// then
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
assertThat(response.getBody()).isEqualTo("ok");

HttpRequest[] recorded = mockClient.retrieveRecordedRequests(request().withPath("/secure"));
assertThat(recorded).hasSize(1);
String authHeader = recorded[0].getFirstHeader("Authorization");
assertThat(authHeader).isNotNull().startsWith("Bearer ");
}

@Test
void restTemplateDoesNotAddAuthorizationHeaderWhenOauth2Disabled() {
// given ConfigClientProperties with OAuth2 disabled
ConfigClientProperties props = new ConfigClientProperties();
props.getOauth2().setEnabled(false); // explicitly disabled

ConfigClientRequestTemplateFactory factory = new ConfigClientRequestTemplateFactory(log, props);
RestTemplate restTemplate = factory.create();

// when
String url = "http://localhost:" + mockServer.getLocalPort() + "/secure";

assertThatThrownBy(() -> restTemplate.getForEntity(URI.create(url), String.class))
.isInstanceOf(org.springframework.web.client.HttpClientErrorException.Unauthorized.class);

// then

HttpRequest[] recorded = mockClient.retrieveRecordedRequests(request().withPath("/secure"));
assertThat(recorded).hasSize(1); // only this test's request
assertThat(recorded[0].containsHeader("Authorization")).isFalse();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"realm": "test-realm",
"enabled": true,
"clients": [
{
"clientId": "config-client",
"secret": "my-client-secret",
"name": "Config Client",
"protocol": "openid-connect",
"publicClient": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": true,
"redirectUris": ["*"],
"webOrigins": ["*"]
}
]
}

4 changes: 4 additions & 0 deletions spring-cloud-config-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@
<artifactId>spring-boot-starter-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aspectj</artifactId>
Expand Down
Loading
Loading