This repository has been archived by the owner on May 31, 2022. It is now read-only.
/
ResourceServerConfigurationTests.java
428 lines (381 loc) · 17.3 KB
/
ResourceServerConfigurationTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
* Copyright 2006-2011 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.security.oauth2.config.annotation;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author Dave Syer
*
*/
public class ResourceServerConfigurationTests {
private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();
private OAuth2AccessToken token;
private OAuth2Authentication authentication;
@Rule
public ExpectedException expected = ExpectedException.none();
@Before
public void init() {
token = new DefaultOAuth2AccessToken("FOO");
ClientDetails client = new BaseClientDetails("client", null, "read", "client_credentials", "ROLE_CLIENT");
authentication = new OAuth2Authentication(
new TokenRequest(null, "client", null, "client_credentials").createOAuth2Request(client), null);
tokenStore.clear();
}
@Test
public void testDefaults() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ResourceServerContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized());
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
.andExpect(MockMvcResultMatchers.status().isNotFound());
context.close();
}
@Test
public void testWithAuthServer() throws Exception {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ResourceServerAndAuthorizationServerContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.header().string("WWW-Authenticate", containsString("Bearer")));
mvc.perform(MockMvcRequestBuilders.post("/oauth/token"))
.andExpect(MockMvcResultMatchers.header().string("WWW-Authenticate", containsString("Basic")));
mvc.perform(MockMvcRequestBuilders.get("/oauth/authorize").accept(MediaType.TEXT_HTML))
.andExpect(MockMvcResultMatchers.redirectedUrl("http://localhost/login"));
mvc.perform(MockMvcRequestBuilders.post("/oauth/token").header("Authorization",
"Basic " + new String(Base64.encode("client:secret".getBytes()))))
.andExpect(MockMvcResultMatchers.content().string(containsString("Missing grant type")));
context.close();
}
@Test
public void testWithAuthServerCustomPath() throws Exception {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ResourceServerAndAuthorizationServerCustomPathContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.header().string("WWW-Authenticate", containsString("Bearer")));
mvc.perform(MockMvcRequestBuilders.post("/token"))
.andExpect(MockMvcResultMatchers.header().string("WWW-Authenticate", containsString("Basic")));
mvc.perform(MockMvcRequestBuilders.get("/authorize").accept(MediaType.TEXT_HTML))
.andExpect(MockMvcResultMatchers.redirectedUrl("http://localhost/login"));
mvc.perform(MockMvcRequestBuilders.post("/token").header("Authorization",
"Basic " + new String(Base64.encode("client:secret".getBytes()))))
.andExpect(MockMvcResultMatchers.content().string(containsString("Missing grant type")));
context.close();
}
@Test
public void testWithAuthServerAndGlobalMethodSecurity() throws Exception {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ResourceServerAndAuthorizationServerContextAndGlobalMethodSecurity.class);
context.refresh();
context.close();
}
@Test
public void testCustomTokenServices() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(TokenServicesContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized());
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
.andExpect(MockMvcResultMatchers.status().isNotFound());
context.close();
}
@Test
public void testCustomTokenExtractor() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(TokenExtractorContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer BAR"))
.andExpect(MockMvcResultMatchers.status().isNotFound());
context.close();
}
@Test
public void testCustomExpressionHandler() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(ExpressionHandlerContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
expected.expect(IllegalArgumentException.class);
expected.expectMessage("#oauth2");
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
.andExpect(MockMvcResultMatchers.status().isUnauthorized());
context.close();
}
@Test
public void testCustomAuthenticationEntryPoint() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(AuthenticationEntryPointContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
.andExpect(MockMvcResultMatchers.status().isFound());
context.close();
}
@Test
public void testCustomAuthenticationDetailsSource() throws Exception {
tokenStore.storeAccessToken(token, authentication);
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(new MockServletContext());
context.register(AuthenticationDetailsSourceContext.class);
context.refresh();
MockMvc mvc = buildMockMvc(context);
mvc.perform(MockMvcRequestBuilders.get("/").header("Authorization", "Bearer FOO"))
.andExpect(MockMvcResultMatchers.status().isNotFound());
context.close();
OAuth2AuthenticationDetails authenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
assertEquals("Basic", authenticationDetails.getTokenType());
assertEquals("BAR", authenticationDetails.getTokenValue());
}
private MockMvc buildMockMvc(AnnotationConfigWebApplicationContext context) {
return MockMvcBuilders.webAppContextSetup(context)
.addFilters(new DelegatingFilterProxy(context.getBean("springSecurityFilterChain", Filter.class)))
.build();
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class ResourceServerContext {
@Bean
public TokenStore tokenStore() {
return tokenStore;
}
}
@Configuration
@EnableResourceServer
@EnableAuthorizationServer
@EnableWebSecurity
@EnableWebMvc
protected static class ResourceServerAndAuthorizationServerContext extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("client").secret("secret").scopes("scope");
}
@Configuration
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
}
@Configuration
@EnableResourceServer
@EnableAuthorizationServer
@EnableWebSecurity
@EnableWebMvc
protected static class ResourceServerAndAuthorizationServerCustomPathContext
extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("client").secret("secret").scopes("scope");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.pathMapping("/oauth/token", "/token");
endpoints.pathMapping("/oauth/authorize", "/authorize");
}
@Configuration
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
}
@Configuration
@EnableResourceServer
@EnableAuthorizationServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
protected static class ResourceServerAndAuthorizationServerContextAndGlobalMethodSecurity
extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory();
}
@Autowired
public void setup(AuthenticationManagerBuilder builder) throws Exception {
builder.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class AuthenticationEntryPointContext extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(authenticationEntryPoint());
}
private AuthenticationEntryPoint authenticationEntryPoint() {
return new LoginUrlAuthenticationEntryPoint("/login");
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class TokenExtractorContext extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenExtractor(new TokenExtractor() {
@Override
public Authentication extract(HttpServletRequest request) {
return new PreAuthenticatedAuthenticationToken("FOO", "N/A");
}
}).tokenStore(tokenStore());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().access("#oauth2.isClient()");
}
@Bean
public TokenStore tokenStore() {
return tokenStore;
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class ExpressionHandlerContext extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.expressionHandler(new DefaultWebSecurityExpressionHandler());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().access("#oauth2.isClient()");
}
@Bean
public TokenStore tokenStore() {
return tokenStore;
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class TokenServicesContext {
@Bean
protected ClientDetailsService clientDetailsService() {
InMemoryClientDetailsService service = new InMemoryClientDetailsService();
service.setClientDetailsStore(
Collections.singletonMap("client", new BaseClientDetails("client", null, null, null, null)));
return service;
}
@Bean
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setClientDetailsService(clientDetailsService());
return tokenServices;
}
@Bean
public TokenStore tokenStore() {
return tokenStore;
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
protected static class AuthenticationDetailsSourceContext extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationDetailsSource(
new AuthenticationDetailsSource<HttpServletRequest, OAuth2AuthenticationDetails>() {
@Override
public OAuth2AuthenticationDetails buildDetails(HttpServletRequest request) {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, "Basic");
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, "BAR");
return new OAuth2AuthenticationDetails(request);
}
});
}
@Bean
public TokenStore tokenStore() {
return tokenStore;
}
}
}