Skip to content

Commit ecb13aa

Browse files
committed
Resource Server JWE Sample
Issue: gh-4435
1 parent 37d108c commit ecb13aa

13 files changed

+641
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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. This resource server is configured to accept JWE-encrypted tokens.
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 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 decrypts the token and subsquently verifies it 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=eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.IyeWtsTonaiWJdoT13B0M7gpqVxAirVGlfqFI4TOmTRcVHICs_ESezS7fa0ODS9XYdwklTtG7hH39yeeMzr2Zo1Ghh-m36fdoqQrV1Do04rUvuTjqbgyNffeZEGB6rquJ-cyAVjp_Oljy10-Bbnw7CeVGwNBSVo9UCB5j49OlNWhLxFpYARFmOlYpXj-s4Q4JiqV6EvjDAYeohAR4QQmND3qoxR-s2I6SLcIho0sSSpUlhrRiqu2uvWefHDcZJdW2WYWnxLHxhzNu3CfnLiqhhaA_YA_iWXR9FYnPDCf_4q3FgSXcgttXzomFKAx5DwnE_dXvsCvpWxslZMU1UIiLA.MHOrrza2GQ9_5PIv.zU4tfhxT6apWBC3stBwQmGlCQBltWVQe4dFIykybWWBFqxo1bf2BZ37twzoEIFXG9jSYEMH4mvBXPWSvn66t-_jnqLnKTJst2plBjhagGCAoLNWXVKeYNp67o-lKOD_JJQFqsRw4oE05VSgRr14MZeaUBFcU3A_kKxMXOu899DKfXBGJvj75H7lDyd8RUXTb-OSWWfUiJc6Y5AUy1zCZCN9yfDsCXt9heTsZANy92Oou9sMFaXkYzyums5OtkBtLFzyuNMEoNioRehTV-FTuL8tDRB1mNhHObwsBfFbR6M1jJK37pHUXGtko-yZ6NGwxyLtwGh4uU2jzE614rQzuzR8aHaHxOkUs1pBTZ8AcRt41snByOe-KU0adthHxedobFiQQBoQ05DgSU7DO6hsK0uVBDF3eG2KjH4L2lZy-WugloLHhdguUoO9F0zUx15-XZO4EVzmhy8xfH2tSXz98eKzz9Dv0DdGnrBL9cK2MM88N1zoq5u4NdlnE12HvuesB7GKdMwZx1-gTw_pzP81TzcctJWl6ETK09Uc.jk0O8qc4Fvip856stDz05Q
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=eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.CRBAEgvQhpB6pPQhpkTAKpsDai1FDcvkDSRig1R3OI-g18JdTe-qDhzWwP-hV3aCwFwHxQ_g8Z8OIZvhyKpQaPwBb72UeLqqhzSIkm0gEsmmjYg1vEGOrDH5_Fqlm0LnAnXTmsbOIWYIj11ZuenI2lEmMCkVwqth0RlzakdcHRXiuDTEln_trhZpE2j80X-9rS2gZy9Raa9VLir3-F3wC0GKPEL6e3x1OygC03ix9uyXS3vpTsU9zlgoYADZyaLeOF1mCG4mQhvXs7IPmPbwNsElJwKh0xSQCHvNOQShprlvd3cHiUFKYw9fXphY1O-AUYcRzHk4DjoBdkGNQMy_Kw.KtC_z674rYBtDgkN.e8QU50Iq1JHkn-1USSxpjEkbrukb4cobvlQRK40iXGAKVIuOod4bSq5fDpIAPHugqIf-_zGsvr-2OCOdzhtBikL46wU7UdZppxPWtk-X6kl33zH_XObRMaGfe-hLxt3RPxRVn7I1Hp6tGW1Rkxyf_ESq4XlcbbrkhDoIz_G_LKXJhvQ-xahW2e0AUc7RZSucns4XUeq9xX_dd7Ht-o1TmQI9WFoFc1l7oh9GtQ6GZMsghnZ1VrbIS2L7jSYiSsD2JqSv1LLtOGj_FBA0ufhqM3LloGiwflEwAryMD10oNb73WonKEycEj1rBsTIKW7SHkI-VkrQA4-8N-aLWgHwDnzyPZmyNyKpqUMvhjIE_0w6oqU4HpN7J5nfBEIAtpPZ_pDkwAdxCQ7JV3zfiUnF7ZQ3q1PnSId315si02ZN9-wRSrMHcHnboQN1Hs4xCAfGyClVyLpCzfa_fAehjt6v1DjgjbzwSjr_LdNmWTvXYBhNO8Jq9Vb7axksrdwksD3pYNMY8cRZxP-LO0V5Sv1_kT_Hf2yLo2iTwB8n8szzGrJ4QQLb5Znu7Sv-M2x52cnIDMiorP3LNpFk.G85FuMSm-8bGumFAStiFQA
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 encrypt using the public key available in the sample.
81+
Also it must support JWTs that either use the "scope" or "scp" attribute._
82+
83+
To change the sample to point at your Authorization Server, simply find this property in the `application.yml`:
84+
85+
```yaml
86+
spring:
87+
security:
88+
oauth2:
89+
resourceserver:
90+
jwt:
91+
jwk-set-uri: ${mockwebserver.url}/.well-known/jwks.json
92+
```
93+
94+
And change the property to your Authorization Server's JWK set endpoint:
95+
96+
```yaml
97+
spring:
98+
security:
99+
oauth2:
100+
resourceserver:
101+
jwt:
102+
jwk-set-uri: https://localhost:9031/pf/JWKS
103+
```
104+
105+
If your Authorization Server does not support RSA_OAEP_256 or AESGCM, then you can change these values in `OAuth2ResourceServerSecurityConfiguration`:
106+
107+
```java
108+
109+
```
110+
111+
And then you can run the app the same as before:
112+
113+
```bash
114+
./gradlew bootRun
115+
```
116+
117+
Make sure to obtain valid tokens from your Authorization Server in order to play with the sample Resource Server.
118+
To use the `/` endpoint, any valid token from your Authorization Server will do.
119+
To use the `/message` endpoint, the token should have the `message:read` scope.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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.squareup.okhttp3:mockwebserver'
10+
11+
testCompile project(':spring-security-test')
12+
testCompile 'org.springframework.boot:spring-boot-starter-test'
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2002-2017 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+
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 = "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.IyeWtsTonaiWJdoT13B0M7gpqVxAirVGlfqFI4TOmTRcVHICs_ESezS7fa0ODS9XYdwklTtG7hH39yeeMzr2Zo1Ghh-m36fdoqQrV1Do04rUvuTjqbgyNffeZEGB6rquJ-cyAVjp_Oljy10-Bbnw7CeVGwNBSVo9UCB5j49OlNWhLxFpYARFmOlYpXj-s4Q4JiqV6EvjDAYeohAR4QQmND3qoxR-s2I6SLcIho0sSSpUlhrRiqu2uvWefHDcZJdW2WYWnxLHxhzNu3CfnLiqhhaA_YA_iWXR9FYnPDCf_4q3FgSXcgttXzomFKAx5DwnE_dXvsCvpWxslZMU1UIiLA.MHOrrza2GQ9_5PIv.zU4tfhxT6apWBC3st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xPWtk-X6kl33zH_XObRMaGfe-hLxt3RPxRVn7I1Hp6tGW1Rkxyf_ESq4XlcbbrkhDoIz_G_LKXJhvQ-xahW2e0AUc7RZSucns4XUeq9xX_dd7Ht-o1TmQI9WFoFc1l7oh9GtQ6GZMsghnZ1VrbIS2L7jSYiSsD2JqSv1LLtOGj_FBA0ufhqM3LloGiwflEwAryMD10oNb73WonKEycEj1rBsTIKW7SHkI-VkrQA4-8N-aLWgHwDnzyPZmyNyKpqUMvhjIE_0w6oqU4HpN7J5nfBEIAtpPZ_pDkwAdxCQ7JV3zfiUnF7ZQ3q1PnSId315si02ZN9-wRSrMHcHnboQN1Hs4xCAfGyClVyLpCzfa_fAehjt6v1DjgjbzwSjr_LdNmWTvXYBhNO8Jq9Vb7axksrdwksD3pYNMY8cRZxP-LO0V5Sv1_kT_Hf2yLo2iTwB8n8szzGrJ4QQLb5Znu7Sv-M2x52cnIDMiorP3LNpFk.G85FuMSm-8bGumFAStiFQA";
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-2018 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.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)