/
SecurityAutoConfigurationTests.java
348 lines (287 loc) · 13.6 KB
/
SecurityAutoConfigurationTests.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
/*
* Copyright 2012-2021 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.autoconfigure.security.servlet;
import java.security.interfaces.RSAPublicKey;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.test.City;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.mock.web.MockServletContext;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.AuthenticationException;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SecurityAutoConfiguration}.
*
* @author Dave Syer
* @author Rob Winch
* @author Andy Wilkinson
* @author Madhura Bhave
*/
class SecurityAutoConfigurationTests {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner().withConfiguration(
AutoConfigurations.of(SecurityAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class));
@Test
void testWebConfiguration() {
this.contextRunner.run((context) -> {
assertThat(context.getBean(AuthenticationManagerBuilder.class)).isNotNull();
assertThat(context.getBean(FilterChainProxy.class).getFilterChains()).hasSize(1);
});
}
@Test
void enableWebSecurityIsConditionalOnClass() {
this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config"))
.run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain"));
}
@Test
void filterChainBeanIsConditionalOnClassSecurityFilterChain() {
this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class))
.run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class));
}
@Test
void securityConfigurerBacksOffWhenOtherSecurityFilterChainBeanPresent() {
this.contextRunner.withUserConfiguration(TestSecurityFilterChainConfig.class).run((context) -> {
assertThat(context.getBeansOfType(SecurityFilterChain.class).size()).isEqualTo(1);
assertThat(context.containsBean("testSecurityFilterChain")).isTrue();
});
}
@Test
void securityConfigurerBacksOffWhenOtherWebSecurityAdapterBeanPresent() {
this.contextRunner.withUserConfiguration(WebSecurity.class).run((context) -> {
assertThat(context.getBeansOfType(WebSecurityConfigurerAdapter.class).size()).isEqualTo(1);
assertThat(context.containsBean("securityAutoConfigurationTests.WebSecurity")).isTrue();
});
}
@Test
void testDefaultFilterOrderWithSecurityAdapter() {
this.contextRunner
.withConfiguration(AutoConfigurations.of(WebSecurity.class, SecurityFilterAutoConfiguration.class))
.run((context) -> assertThat(
context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class)
.getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100));
}
@Test
void testFilterIsNotRegisteredInNonWeb() {
try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) {
customContext.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class);
customContext.refresh();
assertThat(customContext.containsBean("securityFilterChainRegistration")).isFalse();
}
}
@Test
void defaultAuthenticationEventPublisherRegistered() {
this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class))
.isInstanceOf(DefaultAuthenticationEventPublisher.class));
}
@Test
void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() {
this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class)
.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf(
AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class));
}
@Test
void testDefaultFilterOrder() {
this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class))
.run((context) -> assertThat(
context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class)
.getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100));
}
@Test
void testCustomFilterOrder() {
this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class))
.withPropertyValues("spring.security.filter.order:12345")
.run((context) -> assertThat(
context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class)
.getOrder()).isEqualTo(12345));
}
@Test
void testJpaCoexistsHappily() {
this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testsecdb")
.withUserConfiguration(EntityConfiguration.class)
.withConfiguration(
AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class))
.run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull());
// This can fail if security @Conditionals force early instantiation of the
// HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found)
}
@Test
void testSecurityEvaluationContextExtensionSupport() {
this.contextRunner
.run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull());
}
@Test
void defaultFilterDispatcherTypes() {
this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class))
.run((context) -> {
DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class);
assertThat(bean)
.extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class))
.containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST);
});
}
@Test
void customFilterDispatcherTypes() {
this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR")
.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> {
DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class);
assertThat(bean)
.extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class))
.containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR);
});
}
@Test
void emptyFilterDispatcherTypesDoNotThrowException() {
this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:")
.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> {
DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration",
DelegatingFilterProxyRegistrationBean.class);
assertThat(bean)
.extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class))
.isEmpty();
});
}
@Test
void whenAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() {
this.contextRunner.withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class)
.withPropertyValues("jwt.public-key=classpath:public-key-location")
.run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull());
}
@Test
void whenTheBeanFactoryHasAConversionServiceAndAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() {
this.contextRunner
.withInitializer(
(context) -> context.getBeanFactory().setConversionService(new ApplicationConversionService()))
.withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class)
.withPropertyValues("jwt.public-key=classpath:public-key-location")
.run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull());
}
@Test
@SuppressWarnings("unchecked")
void filterRegistrationBeanForErrorPageSecurityInterceptor() {
this.contextRunner.withInitializer((context) -> context.setServletContext(new MockServletContext()))
.run(((context) -> {
FilterRegistrationBean<?> bean = context.getBean(FilterRegistrationBean.class);
assertThat(bean.getFilter()).isInstanceOf(ErrorPageSecurityFilter.class);
EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils
.getField(bean, "dispatcherTypes");
assertThat(dispatcherTypes).containsExactly(DispatcherType.ERROR);
}));
}
@Test
void filterForErrorPageSecurityInterceptorWhenWebInvocationPrivilegeEvaluatorNotPresent() {
this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config"))
.run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter"));
}
@Test
void filterForErrorPageSecurityInterceptorConditionalOnClass() {
this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.web"))
.run((context) -> assertThat(context).doesNotHaveBean("errorPageSecurityFilter"));
}
@Configuration(proxyBeanMethods = false)
@TestAutoConfigurationPackage(City.class)
static class EntityConfiguration {
}
@Configuration(proxyBeanMethods = false)
static class AuthenticationEventPublisherConfiguration {
@Bean
AuthenticationEventPublisher authenticationEventPublisher() {
return new TestAuthenticationEventPublisher();
}
class TestAuthenticationEventPublisher implements AuthenticationEventPublisher {
@Override
public void publishAuthenticationSuccess(Authentication authentication) {
}
@Override
public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) {
}
}
}
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
static class WebSecurity extends WebSecurityConfigurerAdapter {
}
@Configuration(proxyBeanMethods = false)
static class TestSecurityFilterChainConfig {
@Bean
SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception {
return http.antMatcher("/**").authorizeRequests((authorize) -> authorize.anyRequest().authenticated())
.build();
}
}
@Configuration(proxyBeanMethods = false)
static class ConverterConfiguration {
@Bean
@ConfigurationPropertiesBinding
Converter<String, TargetType> targetTypeConverter() {
return new Converter<String, TargetType>() {
@Override
public TargetType convert(String input) {
return new TargetType();
}
};
}
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(JwtProperties.class)
static class PropertiesConfiguration {
}
@ConfigurationProperties("jwt")
static class JwtProperties {
private RSAPublicKey publicKey;
RSAPublicKey getPublicKey() {
return this.publicKey;
}
void setPublicKey(RSAPublicKey publicKey) {
this.publicKey = publicKey;
}
}
static class TargetType {
}
}