|
| 1 | +/* |
| 2 | + * Copyright 2013-present the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.cloud.config.client; |
| 18 | + |
| 19 | +import java.net.URI; |
| 20 | + |
| 21 | +import dasniko.testcontainers.keycloak.KeycloakContainer; |
| 22 | +import org.apache.commons.logging.Log; |
| 23 | +import org.apache.commons.logging.LogFactory; |
| 24 | +import org.junit.jupiter.api.AfterAll; |
| 25 | +import org.junit.jupiter.api.BeforeAll; |
| 26 | +import org.junit.jupiter.api.BeforeEach; |
| 27 | +import org.junit.jupiter.api.Tag; |
| 28 | +import org.junit.jupiter.api.Test; |
| 29 | +import org.junit.jupiter.api.TestInstance; |
| 30 | +import org.mockserver.client.MockServerClient; |
| 31 | +import org.mockserver.integration.ClientAndServer; |
| 32 | +import org.mockserver.model.HttpRequest; |
| 33 | +import org.mockserver.model.MediaType; |
| 34 | +import org.testcontainers.junit.jupiter.Container; |
| 35 | +import org.testcontainers.junit.jupiter.Testcontainers; |
| 36 | + |
| 37 | +import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientProperties; |
| 38 | +import org.springframework.http.ResponseEntity; |
| 39 | +import org.springframework.web.client.RestTemplate; |
| 40 | + |
| 41 | +import static org.assertj.core.api.Assertions.assertThat; |
| 42 | +import static org.assertj.core.api.Assertions.assertThatThrownBy; |
| 43 | +import static org.mockserver.model.HttpRequest.request; |
| 44 | +import static org.mockserver.model.HttpResponse.response; |
| 45 | + |
| 46 | +/** |
| 47 | + * IntegrationTest for OAuth2 support in ConfigClientRequestTemplateFactory using Keycloak |
| 48 | + * Test container as the Authorization Server and MockServer as a protected resource |
| 49 | + * server. |
| 50 | + */ |
| 51 | +@Tag("DockerRequired") |
| 52 | +@Testcontainers |
| 53 | +@TestInstance(TestInstance.Lifecycle.PER_CLASS) |
| 54 | +class ConfigClientRequestTemplateFactoryOAuth2Tests { |
| 55 | + |
| 56 | + private static final Log log = LogFactory.getLog(ConfigClientRequestTemplateFactoryOAuth2Tests.class); |
| 57 | + |
| 58 | + @Container |
| 59 | + static KeycloakContainer keycloak = new KeycloakContainer().withRealmImportFile("test-realm.json"); // classpath |
| 60 | + // resource |
| 61 | + |
| 62 | + private ClientAndServer mockServer; |
| 63 | + |
| 64 | + private MockServerClient mockClient; |
| 65 | + |
| 66 | + @BeforeAll |
| 67 | + void startMockServer() { |
| 68 | + mockServer = ClientAndServer.startClientAndServer(0); |
| 69 | + mockClient = new MockServerClient("localhost", mockServer.getLocalPort()); |
| 70 | + } |
| 71 | + |
| 72 | + @BeforeEach |
| 73 | + void resetExpectations() { |
| 74 | + mockClient.clear(request().withPath("/secure")); |
| 75 | + mockClient.when(request().withMethod("GET").withPath("/secure")).respond(request -> { |
| 76 | + if (request.containsHeader("Authorization")) { |
| 77 | + String authHeader = request.getFirstHeader("Authorization"); |
| 78 | + if (authHeader != null && authHeader.startsWith("Bearer ")) { |
| 79 | + return response().withStatusCode(200).withContentType(MediaType.TEXT_PLAIN).withBody("ok"); |
| 80 | + } |
| 81 | + } |
| 82 | + return response().withStatusCode(401); |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + @AfterAll |
| 87 | + void tearDown() { |
| 88 | + if (mockClient != null) { |
| 89 | + mockClient.close(); |
| 90 | + } |
| 91 | + if (mockServer != null) { |
| 92 | + mockServer.stop(); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + @Test |
| 97 | + void restTemplateAddsBearerTokenFromKeycloakUsingClientCredentials() { |
| 98 | + // given OAuth2 client configuration pointing to Keycloak token endpoint |
| 99 | + String tokenUri = keycloak.getAuthServerUrl() + "/realms/test-realm/protocol/openid-connect/token"; |
| 100 | + |
| 101 | + ConfigClientProperties props = new ConfigClientProperties(); |
| 102 | + props.getOauth2().setEnabled(true); |
| 103 | + |
| 104 | + OAuth2ClientProperties.Provider provider = props.getOauth2().getProvider(); |
| 105 | + provider.setTokenUri(tokenUri); |
| 106 | + |
| 107 | + OAuth2ClientProperties.Registration registration = props.getOauth2().getRegistration(); |
| 108 | + registration.setClientId("config-client"); |
| 109 | + registration.setClientSecret("my-client-secret"); |
| 110 | + registration.setAuthorizationGrantType("client_credentials"); |
| 111 | + |
| 112 | + ConfigClientRequestTemplateFactory factory = new ConfigClientRequestTemplateFactory(log, props); |
| 113 | + RestTemplate restTemplate = factory.create(); |
| 114 | + |
| 115 | + // when |
| 116 | + String url = "http://localhost:" + mockServer.getLocalPort() + "/secure"; |
| 117 | + ResponseEntity<String> response = restTemplate.getForEntity(URI.create(url), String.class); |
| 118 | + |
| 119 | + // then |
| 120 | + assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); |
| 121 | + assertThat(response.getBody()).isEqualTo("ok"); |
| 122 | + |
| 123 | + HttpRequest[] recorded = mockClient.retrieveRecordedRequests(request().withPath("/secure")); |
| 124 | + assertThat(recorded).hasSize(1); |
| 125 | + String authHeader = recorded[0].getFirstHeader("Authorization"); |
| 126 | + assertThat(authHeader).isNotNull().startsWith("Bearer "); |
| 127 | + } |
| 128 | + |
| 129 | + @Test |
| 130 | + void restTemplateDoesNotAddAuthorizationHeaderWhenOauth2Disabled() { |
| 131 | + // given ConfigClientProperties with OAuth2 disabled |
| 132 | + ConfigClientProperties props = new ConfigClientProperties(); |
| 133 | + props.getOauth2().setEnabled(false); // explicitly disabled |
| 134 | + |
| 135 | + ConfigClientRequestTemplateFactory factory = new ConfigClientRequestTemplateFactory(log, props); |
| 136 | + RestTemplate restTemplate = factory.create(); |
| 137 | + |
| 138 | + // when |
| 139 | + String url = "http://localhost:" + mockServer.getLocalPort() + "/secure"; |
| 140 | + |
| 141 | + assertThatThrownBy(() -> restTemplate.getForEntity(URI.create(url), String.class)) |
| 142 | + .isInstanceOf(org.springframework.web.client.HttpClientErrorException.Unauthorized.class); |
| 143 | + |
| 144 | + // then |
| 145 | + |
| 146 | + HttpRequest[] recorded = mockClient.retrieveRecordedRequests(request().withPath("/secure")); |
| 147 | + assertThat(recorded).hasSize(1); // only this test's request |
| 148 | + assertThat(recorded[0].containsHeader("Authorization")).isFalse(); |
| 149 | + } |
| 150 | + |
| 151 | +} |
0 commit comments