Skip to content

Commit ae1f287

Browse files
committed
Resource Server Opaque Token Sample
Issue: gh-5200
1 parent fee65dc commit ae1f287

11 files changed

+597
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
= OAuth 2.0 Resource Server Sample
2+
3+
This sample demonstrates integrating Resource Server with a mock Authorization Server, though it can be modified to integrate
4+
with your favorite Authorization Server.
5+
6+
With it, you can run the integration tests or run the application as a stand-alone service to explore how you can
7+
secure your own service with OAuth 2.0 Opaque Bearer Tokens using Spring Security.
8+
9+
== 1. Running the tests
10+
11+
To run the tests, do:
12+
13+
```bash
14+
./gradlew integrationTest
15+
```
16+
17+
Or import the project into your IDE and run `OAuth2ResourceServerApplicationTests` from there.
18+
19+
=== What is it doing?
20+
21+
By default, the tests are pointing at a mock Authorization Server instance.
22+
23+
The tests are configured with a set of hard-coded tokens originally obtained from the mock Authorization Server,
24+
and each makes a query to the Resource Server with their corresponding token.
25+
26+
The Resource Server subsquently verifies with the Authorization Server and authorizes the request, returning the phrase
27+
28+
```bash
29+
Hello, subject!
30+
```
31+
32+
where "subject" is the value of the `sub` field in the JWT returned by the Authorization Server.
33+
34+
== 2. Running the app
35+
36+
To run as a stand-alone application, do:
37+
38+
```bash
39+
./gradlew bootRun
40+
```
41+
42+
Or import the project into your IDE and run `OAuth2ResourceServerApplication` from there.
43+
44+
Once it is up, you can use the following token:
45+
46+
```bash
47+
export TOKEN=00ed5855-1869-47a0-b0c9-0f3ce520aee7
48+
```
49+
50+
And then make this request:
51+
52+
```bash
53+
curl -H "Authorization: Bearer $TOKEN" localhost:8080
54+
```
55+
56+
Which will respond with the phrase:
57+
58+
```bash
59+
Hello, subject!
60+
```
61+
62+
where `subject` is the value of the `sub` field in the JWT returned by the Authorization Server.
63+
64+
Or this:
65+
66+
```bash
67+
export TOKEN=b43d1500-c405-4dc9-b9c9-6cfd966c34c9
68+
69+
curl -H "Authorization: Bearer $TOKEN" localhost:8080/message
70+
```
71+
72+
Will respond with:
73+
74+
```bash
75+
secret message
76+
```
77+
78+
== 2. Testing against other Authorization Servers
79+
80+
_In order to use this sample, your Authorization Server must support Opaque Tokens and the Introspection Endpoint.
81+
82+
To change the sample to point at your Authorization Server, simply find this property in the `application.yml`:
83+
84+
```yaml
85+
spring:
86+
security:
87+
oauth2:
88+
resourceserver:
89+
opaque:
90+
introspection-uri: ${mockwebserver.url}/introspect
91+
introspection-client-id: client
92+
introspection-client-secret: secret
93+
```
94+
95+
And change the property to your Authorization Server's Introspection endpoint, including its client id and secret:
96+
97+
```yaml
98+
spring:
99+
security:
100+
oauth2:
101+
resourceserver:
102+
opaque:
103+
introspection-uri: ${mockwebserver.url}/introspect
104+
```
105+
106+
And then you can run the app the same as before:
107+
108+
```bash
109+
./gradlew bootRun
110+
```
111+
112+
Make sure to obtain valid tokens from your Authorization Server in order to play with the sample Resource Server.
113+
To use the `/` endpoint, any valid token from your Authorization Server will do.
114+
To use the `/message` endpoint, the token should have the `message:read` scope.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
apply plugin: 'io.spring.convention.spring-sample-boot'
2+
3+
dependencies {
4+
compile project(':spring-security-config')
5+
compile project(':spring-security-oauth2-jose')
6+
compile project(':spring-security-oauth2-resource-server')
7+
8+
compile 'org.springframework.boot:spring-boot-starter-web'
9+
compile 'com.nimbusds:oauth2-oidc-sdk'
10+
compile 'com.squareup.okhttp3:mockwebserver'
11+
12+
testCompile project(':spring-security-test')
13+
testCompile 'org.springframework.boot:spring-boot-starter-test'
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2002-2019 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+
* http://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+
package sample;
17+
18+
import org.junit.Test;
19+
import org.junit.runner.RunWith;
20+
21+
import org.springframework.beans.factory.annotation.Autowired;
22+
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
23+
import org.springframework.boot.test.context.SpringBootTest;
24+
import org.springframework.http.HttpHeaders;
25+
import org.springframework.mock.web.MockHttpServletRequest;
26+
import org.springframework.test.context.ActiveProfiles;
27+
import org.springframework.test.context.junit4.SpringRunner;
28+
import org.springframework.test.web.servlet.MockMvc;
29+
import org.springframework.test.web.servlet.request.RequestPostProcessor;
30+
31+
import static org.hamcrest.Matchers.containsString;
32+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
33+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
34+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
35+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
36+
37+
/**
38+
* Integration tests for {@link OAuth2ResourceServerApplication}
39+
*
40+
* @author Josh Cummings
41+
*/
42+
@RunWith(SpringRunner.class)
43+
@SpringBootTest
44+
@AutoConfigureMockMvc
45+
@ActiveProfiles("test")
46+
public class OAuth2ResourceServerApplicationITests {
47+
48+
String noScopesToken = "00ed5855-1869-47a0-b0c9-0f3ce520aee7";
49+
String messageReadToken = "b43d1500-c405-4dc9-b9c9-6cfd966c34c9";
50+
51+
@Autowired
52+
MockMvc mvc;
53+
54+
@Test
55+
public void performWhenValidBearerTokenThenAllows()
56+
throws Exception {
57+
58+
this.mvc.perform(get("/").with(bearerToken(this.noScopesToken)))
59+
.andExpect(status().isOk())
60+
.andExpect(content().string(containsString("Hello, subject!")));
61+
}
62+
63+
// -- tests with scopes
64+
65+
@Test
66+
public void performWhenValidBearerTokenThenScopedRequestsAlsoWork()
67+
throws Exception {
68+
69+
this.mvc.perform(get("/message").with(bearerToken(this.messageReadToken)))
70+
.andExpect(status().isOk())
71+
.andExpect(content().string(containsString("secret message")));
72+
}
73+
74+
@Test
75+
public void performWhenInsufficientlyScopedBearerTokenThenDeniesScopedMethodAccess()
76+
throws Exception {
77+
78+
this.mvc.perform(get("/message").with(bearerToken(this.noScopesToken)))
79+
.andExpect(status().isForbidden())
80+
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE,
81+
containsString("Bearer error=\"insufficient_scope\"")));
82+
}
83+
84+
private static class BearerTokenRequestPostProcessor implements RequestPostProcessor {
85+
private String token;
86+
87+
public BearerTokenRequestPostProcessor(String token) {
88+
this.token = token;
89+
}
90+
91+
@Override
92+
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
93+
request.addHeader("Authorization", "Bearer " + this.token);
94+
return request;
95+
}
96+
}
97+
98+
private static BearerTokenRequestPostProcessor bearerToken(String token) {
99+
return new BearerTokenRequestPostProcessor(token);
100+
}
101+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Copyright 2002-2019 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+
* http://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.boot.env;
18+
19+
import org.springframework.beans.factory.DisposableBean;
20+
import org.springframework.boot.SpringApplication;
21+
import org.springframework.core.env.ConfigurableEnvironment;
22+
23+
/**
24+
* @author Rob Winch
25+
*/
26+
public class MockWebServerEnvironmentPostProcessor
27+
implements EnvironmentPostProcessor, DisposableBean {
28+
29+
private final MockWebServerPropertySource propertySource = new MockWebServerPropertySource();
30+
31+
@Override
32+
public void postProcessEnvironment(ConfigurableEnvironment environment,
33+
SpringApplication application) {
34+
environment.getPropertySources().addFirst(this.propertySource);
35+
}
36+
37+
@Override
38+
public void destroy() throws Exception {
39+
this.propertySource.destroy();
40+
}
41+
}

0 commit comments

Comments
 (0)