Add ":servlet:spring-boot:java:oauth2:resource-server:multi-tenancy"
This commit is contained in:
+170
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
* Copyright 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 example;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.RequestPostProcessor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/**
|
||||
* Integration tests for {@link OAuth2ResourceServerApplication}.
|
||||
*
|
||||
* @author Josh Cummings
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("test")
|
||||
public class OAuth2ResourceServerApplicationITests {
|
||||
|
||||
String tenantOneNoScopesToken = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0IiwiZXhwIjo0NjgzODA1MTI4fQ.ULEPdHG-MK5GlrTQMhgqcyug2brTIZaJIrahUeq9zaiwUSdW83fJ7W1IDd2Z3n4a25JY2uhEcoV95lMfccHR6y_2DLrNvfta22SumY9PEDF2pido54LXG6edIGgarnUbJdR4rpRe_5oRGVa8gDx8FnuZsNv6StSZHAzw5OsuevSTJ1UbJm4UfX3wiahFOQ2OI6G-r5TB2rQNdiPHuNyzG5yznUqRIZ7-GCoMqHMaC-1epKxiX8gYXRROuUYTtcMNa86wh7OVDmvwVmFioRcR58UWBRoO1XQexTtOQq_t8KYsrPZhb9gkyW8x2bAQF-d0J0EJY8JslaH6n4RBaZISww";
|
||||
|
||||
String tenantOneMessageReadToken = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0Iiwic2NvcGUiOiJtZXNzYWdlOnJlYWQiLCJleHAiOjQ2ODM4MDUxNDF9.h-j6FKRFdnTdmAueTZCdep45e6DPwqM68ZQ8doIJ1exi9YxAlbWzOwId6Bd0L5YmCmp63gGQgsBUBLzwnZQ8kLUgUOBEC3UzSWGRqMskCY9_k9pX0iomX6IfF3N0PaYs0WPC4hO1s8wfZQ-6hKQ4KigFi13G9LMLdH58PRMK0pKEvs3gCbHJuEPw-K5ORlpdnleUTQIwINafU57cmK3KocTeknPAM_L716sCuSYGvDl6xUTXO7oPdrXhS_EhxLP6KxrpI1uD4Ea_5OWTh7S0Wx5LLDfU6wBG1DowN20d374zepOIEkR-Jnmr_QlR44vmRqS5ncrF-1R0EGcPX49U6A";
|
||||
|
||||
String tenantTwoNoScopesToken = "00ed5855-1869-47a0-b0c9-0f3ce520aee7";
|
||||
|
||||
String tenantTwoMessageReadToken = "b43d1500-c405-4dc9-b9c9-6cfd966c34c9";
|
||||
|
||||
@Autowired
|
||||
MockMvc mvc;
|
||||
|
||||
@Test
|
||||
void tenantOnePerformWhenValidBearerTokenThenAllows()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantOne").with(bearerToken(this.tenantOneNoScopesToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Hello, subject for tenantOne!")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
void tenantOnePerformWhenValidBearerTokenWithServletPathThenAllows()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantOne").servletPath("/tenantOne").with(bearerToken(this.tenantOneNoScopesToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Hello, subject for tenantOne!")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
// -- tests with scopes
|
||||
|
||||
@Test
|
||||
void tenantOnePerformWhenValidBearerTokenThenScopedRequestsAlsoWork()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantOne/message").with(bearerToken(this.tenantOneMessageReadToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("secret message for tenantOne")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
void tenantOnePerformWhenInsufficientlyScopedBearerTokenThenDeniesScopedMethodAccess()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantOne/message").with(bearerToken(this.tenantOneNoScopesToken)))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
|
||||
containsString("Bearer error=\"insufficient_scope\"")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
void tenantTwoPerformWhenValidBearerTokenThenAllows()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantTwo").with(bearerToken(this.tenantTwoNoScopesToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("Hello, subject for tenantTwo!")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
// -- tests with scopes
|
||||
|
||||
@Test
|
||||
void tenantTwoPerformWhenValidBearerTokenThenScopedRequestsAlsoWork()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantTwo/message").with(bearerToken(this.tenantTwoMessageReadToken)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString("secret message for tenantTwo")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
void tenantTwoPerformWhenInsufficientlyScopedBearerTokenThenDeniesScopedMethodAccess()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/tenantTwo/message").with(bearerToken(this.tenantTwoNoScopesToken)))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
|
||||
containsString("Bearer error=\"insufficient_scope\"")));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidTenantPerformWhenValidBearerTokenThenThrowsException()
|
||||
throws Exception {
|
||||
|
||||
// @formatter:off
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() ->
|
||||
this.mvc.perform(get("/tenantThree")
|
||||
.with(bearerToken(this.tenantOneNoScopesToken)))
|
||||
);
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
private static BearerTokenRequestPostProcessor bearerToken(String token) {
|
||||
return new BearerTokenRequestPostProcessor(token);
|
||||
}
|
||||
|
||||
private static class BearerTokenRequestPostProcessor implements RequestPostProcessor {
|
||||
private String token;
|
||||
|
||||
BearerTokenRequestPostProcessor(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
|
||||
request.addHeader("Authorization", "Bearer " + this.token);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 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 example;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* OAuth Resource Server application.
|
||||
* @author Josh Cummings
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class OAuth2ResourceServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OAuth2ResourceServerApplication.class, args);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 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 example;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* A controller demonstrating OAuth2 Resource server.
|
||||
* @author Josh Cummings
|
||||
*/
|
||||
@RestController
|
||||
public class OAuth2ResourceServerController {
|
||||
|
||||
@GetMapping("/{tenantId}")
|
||||
public String index(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal token, @PathVariable("tenantId") String tenantId) {
|
||||
String subject = token.getAttribute("sub");
|
||||
return String.format("Hello, %s for %s!", subject, tenantId);
|
||||
}
|
||||
|
||||
@GetMapping("/{tenantId}/message")
|
||||
public String message(@PathVariable("tenantId") String tenantId) {
|
||||
return String.format("secret message for %s", tenantId);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 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 example;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationManagerResolver;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtBearerTokenAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.OpaqueTokenAuthenticationProvider;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
|
||||
|
||||
/**
|
||||
* OAuth Resource Security configuration.
|
||||
* @author Josh Cummings
|
||||
*/
|
||||
@EnableWebSecurity
|
||||
public class OAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Value("${tenantOne.jwk-set-uri}")
|
||||
String jwkSetUri;
|
||||
|
||||
@Value("${tenantTwo.introspection-uri}")
|
||||
String introspectionUri;
|
||||
|
||||
@Value("${tenantTwo.introspection-client-id}")
|
||||
String introspectionClientId;
|
||||
|
||||
@Value("${tenantTwo.introspection-client-secret}")
|
||||
String introspectionClientSecret;
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.authorizeRequests((requests) -> requests
|
||||
.mvcMatchers("/**/message/**").hasAuthority("SCOPE_message:read")
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.oauth2ResourceServer((resourceServer) -> resourceServer
|
||||
.authenticationManagerResolver(multitenantAuthenticationManager())
|
||||
);
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthenticationManagerResolver<HttpServletRequest> multitenantAuthenticationManager() {
|
||||
Map<String, AuthenticationManager> authenticationManagers = new HashMap<>();
|
||||
authenticationManagers.put("tenantOne", jwt());
|
||||
authenticationManagers.put("tenantTwo", opaque());
|
||||
return (request) -> {
|
||||
String[] pathParts = request.getRequestURI().split("/");
|
||||
String tenantId = (pathParts.length > 0) ? pathParts[1] : null;
|
||||
// @formatter:off
|
||||
return Optional.ofNullable(tenantId)
|
||||
.map(authenticationManagers::get)
|
||||
.orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
|
||||
// @formatter:on
|
||||
};
|
||||
}
|
||||
|
||||
AuthenticationManager jwt() {
|
||||
JwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
|
||||
JwtAuthenticationProvider authenticationProvider = new JwtAuthenticationProvider(jwtDecoder);
|
||||
authenticationProvider.setJwtAuthenticationConverter(new JwtBearerTokenAuthenticationConverter());
|
||||
return authenticationProvider::authenticate;
|
||||
}
|
||||
|
||||
AuthenticationManager opaque() {
|
||||
OpaqueTokenIntrospector introspectionClient =
|
||||
new NimbusOpaqueTokenIntrospector(this.introspectionUri,
|
||||
this.introspectionClientId, this.introspectionClientSecret);
|
||||
return new OpaqueTokenAuthenticationProvider(introspectionClient)::authenticate;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.boot.env;
|
||||
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
|
||||
/**
|
||||
* Adds {@link MockWebServerPropertySource} to the environment.
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class MockWebServerEnvironmentPostProcessor
|
||||
implements EnvironmentPostProcessor, DisposableBean {
|
||||
|
||||
private final MockWebServerPropertySource propertySource = new MockWebServerPropertySource();
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment,
|
||||
SpringApplication application) {
|
||||
environment.getPropertySources().addFirst(this.propertySource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
this.propertySource.destroy();
|
||||
}
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.boot.env;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import okhttp3.mockwebserver.Dispatcher;
|
||||
import okhttp3.mockwebserver.MockResponse;
|
||||
import okhttp3.mockwebserver.MockWebServer;
|
||||
import okhttp3.mockwebserver.RecordedRequest;
|
||||
import okio.Buffer;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
/**
|
||||
* Adds the mock server url.
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class MockWebServerPropertySource extends PropertySource<MockWebServer> implements
|
||||
DisposableBean {
|
||||
|
||||
// introspection endpoint
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse NO_SCOPES_RESPONSE = response(
|
||||
"{\n" +
|
||||
" \"active\": true,\n" +
|
||||
" \"sub\": \"subject\"\n" +
|
||||
" }",
|
||||
200
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse MESSASGE_READ_SCOPE_RESPONSE = response(
|
||||
"{\n" +
|
||||
" \"active\": true,\n" +
|
||||
" \"scope\" : \"message:read\"," +
|
||||
" \"sub\": \"subject\"\n" +
|
||||
" }",
|
||||
200
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse INACTIVE_RESPONSE = response(
|
||||
"{\n" +
|
||||
" \"active\": false,\n" +
|
||||
" }",
|
||||
200
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse BAD_REQUEST_RESPONSE = response(
|
||||
"{ \"message\" : \"This mock authorization server requires a username and password of " +
|
||||
"client/secret and a POST body of token=${token}\" }",
|
||||
400
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse NOT_FOUND_RESPONSE = response(
|
||||
"{ \"message\" : \"This mock authorization server responds to just two requests: POST /introspect" +
|
||||
" and GET /.well-known/jwks.json.\" }",
|
||||
404
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
// jwks endpoint
|
||||
|
||||
// @formatter:off
|
||||
private static final MockResponse JWKS_RESPONSE = response(
|
||||
"{\"keys\":[{\"p\":\"2p-ViY7DE9ZrdWQb544m0Jp7Cv03YCSljqfim9pD4ALhObX0OrAznOiowTjwBky9JGffMwDBVSfJSD9TSU7aH2sbbfi0bZLMdekKAuimudXwUqPDxrrg0BCyvCYgLmKjbVT3zcdylWSog93CNTxGDPzauu-oc0XPNKCXnaDpNvE\",\"kty\":\"RSA\",\"q\":\"sP_QYavrpBvSJ86uoKVGj2AGl78CSsAtpf1ybSY5TwUlorXSdqapRbY69Y271b0aMLzlleUn9ZTBO1dlKV2_dw_lPADHVia8z3pxL-8sUhIXLsgj4acchMk4c9YX-sFh07xENnyZ-_TXm3llPLuL67HUfBC2eKe800TmCYVWc9U\",\"d\":\"bn1nFxCQT4KLTHqo8mo9HvHD0cRNRNdWcKNnnEQkCF6tKbt-ILRyQGP8O40axLd7CoNVG9c9p_-g4-2kwCtLJNv_STLtwfpCY7VN5o6-ZIpfTjiW6duoPrLWq64Hm_4LOBQTiZfUPcLhsuJRHbWqakj-kV_YbUyC2Ocf_dd8IAQcSrAU2SCcDebhDCWwRUFvaa9V5eq0851S9goaA-AJz-JXyePH6ZFr8JxmWkWxYZ5kdcMD-sm9ZbxE0CaEk32l4fE4hR-L8x2dDtjWA-ahKCZ091z-gV3HWtR2JOjvxoNRjxUo3UxaGiFJHWNIl0EYUJZu1Cb-5wIlEI7wPx5mwQ\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"qi\":\"qS0OK48M2CIAA6_4Wdw4EbCaAfcTLf5Oy9t5BOF_PFUKqoSpZ6JsT5H0a_4zkjt-oI969v78OTlvBKbmEyKO-KeytzHBAA5CsLmVcz0THrMSg6oXZqu66MPnvWoZN9FEN5TklPOvBFm8Bg1QZ3k-YMVaM--DLvhaYR95_mqaz50\",\"dp\":\"Too2NozLGD1XrXyhabZvy1E0EuaVFj0UHQPDLSpkZ_2g3BK6Art6T0xmE8RYtmqrKIEIdlI3IliAvyvAx_1D7zWTTRaj-xlZyqJFrnXWL7zj8UxT8PkB-r2E-ILZ3NAi1gxIWezlBTZ8M6NfObDFmbTc_3tJkN_raISo8z_ziIE\",\"dq\":\"U0yhSkY5yOsa9YcMoigGVBWSJLpNHtbg5NypjHrPv8OhWbkOSq7WvSstBkFk5AtyFvvfZLMLIkWWxxGzV0t6f1MoxBtttLrYYyCxwihiiGFhLbAdSuZ1wnxcqA9bC7UVECvrQmVTpsMs8UupfHKbQBpZ8OWAqrnuYNNtG4_4Bt0\",\"n\":\"lygtuZj0lJjqOqIWocF8Bb583QDdq-aaFg8PesOp2-EDda6GqCpL-_NZVOflNGX7XIgjsWHcPsQHsV9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC58CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eqD9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}",
|
||||
200
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
/**
|
||||
* Name of the random {@link PropertySource}.
|
||||
*/
|
||||
public static final String MOCK_WEB_SERVER_PROPERTY_SOURCE_NAME = "mockwebserver";
|
||||
|
||||
private static final String NAME = "mockwebserver.url";
|
||||
|
||||
private static final Log logger = LogFactory.getLog(MockWebServerPropertySource.class);
|
||||
|
||||
private boolean started;
|
||||
|
||||
public MockWebServerPropertySource() {
|
||||
super(MOCK_WEB_SERVER_PROPERTY_SOURCE_NAME, new MockWebServer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getProperty(String name) {
|
||||
if (!name.equals(NAME)) {
|
||||
return null;
|
||||
}
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace("Looking up the url for '" + name + "'");
|
||||
}
|
||||
String url = getUrl();
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
getSource().shutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get's the URL (i.e. "http://localhost:123456")
|
||||
* @return the mock server URL.
|
||||
*/
|
||||
private String getUrl() {
|
||||
MockWebServer mockWebServer = getSource();
|
||||
if (!this.started) {
|
||||
intializeMockWebServer(mockWebServer);
|
||||
}
|
||||
String url = mockWebServer.url("").url().toExternalForm();
|
||||
return url.substring(0, url.length() - 1);
|
||||
}
|
||||
|
||||
private void intializeMockWebServer(MockWebServer mockWebServer) {
|
||||
Dispatcher dispatcher = new Dispatcher() {
|
||||
@Override
|
||||
public MockResponse dispatch(RecordedRequest request) {
|
||||
return doDispatch(request);
|
||||
}
|
||||
};
|
||||
|
||||
mockWebServer.setDispatcher(dispatcher);
|
||||
try {
|
||||
mockWebServer.start();
|
||||
this.started = true;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new RuntimeException("Could not start " + mockWebServer, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private MockResponse doDispatch(RecordedRequest request) {
|
||||
if ("/.well-known/jwks.json".equals(request.getPath())) {
|
||||
return JWKS_RESPONSE;
|
||||
}
|
||||
|
||||
if ("/introspect".equals(request.getPath())) {
|
||||
// @formatter:off
|
||||
return Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION))
|
||||
.filter((authorization) -> isAuthorized(authorization, "client", "secret"))
|
||||
.map((authorization) -> parseBody(request.getBody()))
|
||||
.map((parameters) -> parameters.get("token"))
|
||||
.map((token) -> {
|
||||
if ("00ed5855-1869-47a0-b0c9-0f3ce520aee7".equals(token)) {
|
||||
return NO_SCOPES_RESPONSE;
|
||||
}
|
||||
else if ("b43d1500-c405-4dc9-b9c9-6cfd966c34c9".equals(token)) {
|
||||
return MESSASGE_READ_SCOPE_RESPONSE;
|
||||
}
|
||||
else {
|
||||
return INACTIVE_RESPONSE;
|
||||
}
|
||||
})
|
||||
.orElse(BAD_REQUEST_RESPONSE);
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
return NOT_FOUND_RESPONSE;
|
||||
}
|
||||
|
||||
private boolean isAuthorized(String authorization, String username, String password) {
|
||||
String[] values = new String(Base64.getDecoder().decode(authorization.substring(6))).split(":");
|
||||
return username.equals(values[0]) && password.equals(values[1]);
|
||||
}
|
||||
|
||||
private Map<String, Object> parseBody(Buffer body) {
|
||||
// @formatter:off
|
||||
return Stream.of(body.readUtf8().split("&"))
|
||||
.map((parameter) -> parameter.split("="))
|
||||
.collect(Collectors.toMap((parts) -> parts[0], (parts) -> parts[1]));
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
private static MockResponse response(String body, int status) {
|
||||
// @formatter:off
|
||||
return new MockResponse()
|
||||
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setResponseCode(status)
|
||||
.setBody(body);
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* This provides integration of a {@link okhttp3.mockwebserver.MockWebServer} and the
|
||||
* {@link org.springframework.core.env.Environment}.
|
||||
* @author Rob Winch
|
||||
*/
|
||||
package org.springframework.boot.env;
|
||||
+1
@@ -0,0 +1 @@
|
||||
org.springframework.boot.env.EnvironmentPostProcessor=org.springframework.boot.env.MockWebServerEnvironmentPostProcessor
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
tenantOne.jwk-set-uri: ${mockwebserver.url}/.well-known/jwks.json
|
||||
tenantTwo.introspection-uri: ${mockwebserver.url}/introspect
|
||||
tenantTwo.introspection-client-id: client
|
||||
tenantTwo.introspection-client-secret: secret
|
||||
Reference in New Issue
Block a user