Polish resourceserver samples

- Use ${mockserver.url} instead of mock://
- Consistency between reactive/imperative samples

Fixes: gh-5844
This commit is contained in:
Rob Winch
2018-09-13 14:31:23 -05:00
parent f68141d42a
commit c21b2f31c6
19 changed files with 473 additions and 298 deletions

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2002-2018 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
*
* http://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;
/**
* @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();
}
}

View File

@@ -14,47 +14,26 @@
* limitations under the License.
*/
package sample.provider;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PreDestroy;
package org.springframework.boot.env;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
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;
import java.io.IOException;
/**
* This is a miminal mock server that serves as a placeholder for a real Authorization Server (AS).
*
* For the sample to work, the AS used must support a JWK endpoint.
*
* For the integration tests to work, the AS used must be able to issue a token
* with the following characteristics:
*
* - The token has the "message:read" scope
* - The token has a "sub" of "subject"
* - The token is signed by a RS256 private key whose public key counterpart is served from the JWK endpoint of the AS.
*
* There is also a test that verifies insufficient scope. In that case, the token should have the following characteristics:
*
* - The token is missing the "message:read" scope
* - The token is signed by a RS256 private key whose public key counterpart is served from the JWK endpoint of the AS.
*
* @author Josh Cummings
* @author Rob Winch
*/
public class MockProvider implements EnvironmentPostProcessor {
private MockWebServer server = new MockWebServer();
public class MockWebServerPropertySource extends PropertySource<MockWebServer> implements
DisposableBean {
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-L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public MockProvider() throws IOException {
/**
* 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
*/
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) throws InterruptedException {
@@ -78,38 +102,20 @@ public class MockProvider implements EnvironmentPostProcessor {
}
};
this.server.setDispatcher(dispatcher);
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String uri = environment.getProperty("sample.jwk-set-uri", "mock://localhost:0");
if (uri.startsWith("mock://")) {
try {
this.server.start(URI.create(uri).getPort());
} catch (IOException e) {
throw new IllegalStateException(e);
}
Map<String, Object> properties = new HashMap<>();
String url = this.server.url("/.well-known/jwks.json").toString();
properties.put("sample.jwk-set-uri", url);
MapPropertySource propertySource = new MapPropertySource("mock", properties);
environment.getPropertySources().addFirst(propertySource);
mockWebServer.setDispatcher(dispatcher);
try {
mockWebServer.start();
this.started = true;
} catch (IOException e) {
throw new RuntimeException("Could not start " + mockWebServer, e);
}
}
@PreDestroy
public void shutdown() throws IOException {
this.server.shutdown();
}
private static MockResponse response(String body, int status) {
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(status)
.setBody(body);
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2002-2018 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
*
* http://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;

View File

@@ -15,7 +15,6 @@
*/
package sample;
import org.springframework.beans.factory.annotation.Value;
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;
@@ -25,20 +24,17 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
*/
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${sample.jwk-set-uri}")
String jwkSetUri;
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/message/**").access("hasAuthority('SCOPE_message:read')")
.antMatchers("/message/**").hasAuthority("SCOPE_message:read")
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwkSetUri(this.jwkSetUri);
.jwt();
// @formatter:on
}
}