Skip to content

Commit 2c128e8

Browse files
committed
SecurityMockMvcConfigurer Honors Filter Order
Fixes gh-7265
1 parent a17b75e commit 2c128e8

File tree

4 files changed

+198
-17
lines changed

4 files changed

+198
-17
lines changed

test/spring-security-test.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ dependencies {
1212

1313
provided 'javax.servlet:javax.servlet-api'
1414

15+
testCompile project(path : ':spring-security-config', configuration : 'tests')
1516
testCompile 'com.fasterxml.jackson.core:jackson-databind'
1617
testCompile 'io.projectreactor:reactor-test'
1718
testCompile 'javax.xml.bind:jaxb-api'

test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java

Lines changed: 87 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,20 @@
1616
package org.springframework.security.test.web.servlet.setup;
1717

1818
import javax.servlet.Filter;
19+
import javax.servlet.FilterChain;
20+
import javax.servlet.FilterConfig;
21+
import javax.servlet.ServletException;
22+
import javax.servlet.ServletRequest;
23+
import javax.servlet.ServletResponse;
1924

2025
import org.springframework.security.config.BeanIds;
2126
import org.springframework.test.web.servlet.request.RequestPostProcessor;
2227
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
2328
import org.springframework.test.web.servlet.setup.MockMvcConfigurerAdapter;
2429
import org.springframework.web.context.WebApplicationContext;
2530

31+
import java.io.IOException;
32+
2633
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
2734

2835
/**
@@ -34,43 +41,115 @@
3441
* @since 4.0
3542
*/
3643
final class SecurityMockMvcConfigurer extends MockMvcConfigurerAdapter {
37-
private Filter springSecurityFilterChain;
44+
private final DelegateFilter delegateFilter;
3845

3946
/**
4047
* Creates a new instance
4148
*/
4249
SecurityMockMvcConfigurer() {
50+
this.delegateFilter = new DelegateFilter();
4351
}
4452

4553
/**
4654
* Creates a new instance with the provided {@link javax.servlet.Filter}
4755
* @param springSecurityFilterChain the {@link javax.servlet.Filter} to use
4856
*/
4957
SecurityMockMvcConfigurer(Filter springSecurityFilterChain) {
50-
this.springSecurityFilterChain = springSecurityFilterChain;
58+
this.delegateFilter = new DelegateFilter(springSecurityFilterChain);
59+
}
60+
61+
@Override
62+
public void afterConfigurerAdded(ConfigurableMockMvcBuilder<?> builder) {
63+
builder.addFilters(this.delegateFilter);
5164
}
5265

5366
@Override
5467
public RequestPostProcessor beforeMockMvcCreated(
5568
ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) {
5669
String securityBeanId = BeanIds.SPRING_SECURITY_FILTER_CHAIN;
57-
if (this.springSecurityFilterChain == null
70+
if (getSpringSecurityFilterChain() == null
5871
&& context.containsBean(securityBeanId)) {
59-
this.springSecurityFilterChain = context.getBean(securityBeanId,
60-
Filter.class);
72+
setSpringSecurityFitlerChain(context.getBean(securityBeanId,
73+
Filter.class));
6174
}
6275

63-
if (this.springSecurityFilterChain == null) {
76+
if (getSpringSecurityFilterChain() == null) {
6477
throw new IllegalStateException(
6578
"springSecurityFilterChain cannot be null. Ensure a Bean with the name "
6679
+ securityBeanId
6780
+ " implementing Filter is present or inject the Filter to be used.");
6881
}
6982

70-
builder.addFilters(this.springSecurityFilterChain);
83+
// This is used by other test support to obtain the FilterChainProxy
7184
context.getServletContext().setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN,
72-
this.springSecurityFilterChain);
85+
getSpringSecurityFilterChain());
7386

7487
return testSecurityContext();
7588
}
89+
90+
private void setSpringSecurityFitlerChain(Filter filter) {
91+
this.delegateFilter.setDelegate(filter);
92+
}
93+
94+
private Filter getSpringSecurityFilterChain() {
95+
return this.delegateFilter.delegate;
96+
}
97+
98+
/**
99+
* Allows adding in {@link #afterConfigurerAdded(ConfigurableMockMvcBuilder)} to preserve Filter order and then
100+
* lazily set the delegate in {@link #beforeMockMvcCreated(ConfigurableMockMvcBuilder, WebApplicationContext)}.
101+
*
102+
* {@link org.springframework.web.filter.DelegatingFilterProxy} is not used because it is not easy to lazily set
103+
* the delegate or get the delegate which is necessary for the test infrastructure.
104+
*/
105+
static class DelegateFilter implements Filter {
106+
107+
private Filter delegate;
108+
109+
DelegateFilter() {
110+
}
111+
112+
DelegateFilter(Filter delegate) {
113+
this.delegate = delegate;
114+
}
115+
116+
void setDelegate(Filter delegate) {
117+
this.delegate = delegate;
118+
}
119+
120+
Filter getDelegate() {
121+
return this.delegate;
122+
}
123+
124+
@Override
125+
public void init(FilterConfig filterConfig) throws ServletException {
126+
this.delegate.init(filterConfig);
127+
}
128+
129+
@Override
130+
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
131+
throws IOException, ServletException {
132+
this.delegate.doFilter(request, response, chain);
133+
}
134+
135+
@Override
136+
public void destroy() {
137+
this.delegate.destroy();
138+
}
139+
140+
@Override
141+
public int hashCode() {
142+
return this.delegate.hashCode();
143+
}
144+
145+
@Override
146+
public boolean equals(Object obj) {
147+
return this.delegate.equals(obj);
148+
}
149+
150+
@Override
151+
public String toString() {
152+
return this.delegate.toString();
153+
}
154+
}
76155
}

test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,24 @@
1515
*/
1616
package org.springframework.security.test.web.servlet.setup;
1717

18-
import javax.servlet.Filter;
19-
import javax.servlet.ServletContext;
20-
2118
import org.junit.Before;
2219
import org.junit.Test;
2320
import org.junit.runner.RunWith;
21+
import org.mockito.ArgumentCaptor;
2422
import org.mockito.Mock;
2523
import org.mockito.junit.MockitoJUnitRunner;
26-
2724
import org.springframework.security.config.BeanIds;
2825
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
2926
import org.springframework.web.context.WebApplicationContext;
3027

31-
import static org.mockito.Matchers.anyString;
32-
import static org.mockito.Matchers.eq;
28+
import javax.servlet.Filter;
29+
import javax.servlet.ServletContext;
30+
import javax.servlet.ServletException;
31+
import java.io.IOException;
32+
33+
import static org.assertj.core.api.Assertions.assertThat;
34+
import static org.mockito.ArgumentMatchers.anyString;
35+
import static org.mockito.ArgumentMatchers.eq;
3336
import static org.mockito.Mockito.verify;
3437
import static org.mockito.Mockito.when;
3538

@@ -56,9 +59,10 @@ public void beforeMockMvcCreatedOverrideBean() throws Exception {
5659
returnFilterBean();
5760
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(this.filter);
5861

62+
configurer.afterConfigurerAdded(this.builder);
5963
configurer.beforeMockMvcCreated(this.builder, this.context);
6064

61-
verify(this.builder).addFilters(this.filter);
65+
assertFilterAdded(this.filter);
6266
verify(this.servletContext).setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN,
6367
this.filter);
6468
}
@@ -68,27 +72,37 @@ public void beforeMockMvcCreatedBean() throws Exception {
6872
returnFilterBean();
6973
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
7074

75+
configurer.afterConfigurerAdded(this.builder);
7176
configurer.beforeMockMvcCreated(this.builder, this.context);
7277

73-
verify(this.builder).addFilters(this.beanFilter);
78+
assertFilterAdded(this.beanFilter);
7479
}
7580

7681
@Test
7782
public void beforeMockMvcCreatedNoBean() throws Exception {
7883
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(this.filter);
7984

85+
configurer.afterConfigurerAdded(this.builder);
8086
configurer.beforeMockMvcCreated(this.builder, this.context);
8187

82-
verify(this.builder).addFilters(this.filter);
88+
assertFilterAdded(this.filter);
8389
}
8490

8591
@Test(expected = IllegalStateException.class)
8692
public void beforeMockMvcCreatedNoFilter() throws Exception {
8793
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
8894

95+
configurer.afterConfigurerAdded(this.builder);
8996
configurer.beforeMockMvcCreated(this.builder, this.context);
9097
}
9198

99+
private void assertFilterAdded(Filter filter) throws IOException, ServletException {
100+
ArgumentCaptor<SecurityMockMvcConfigurer.DelegateFilter> filterArg = ArgumentCaptor.forClass(
101+
SecurityMockMvcConfigurer.DelegateFilter.class);
102+
verify(this.builder).addFilters(filterArg.capture());
103+
assertThat(filterArg.getValue().getDelegate()).isEqualTo(filter);
104+
}
105+
92106
private void returnFilterBean() {
93107
when(this.context.containsBean(anyString())).thenReturn(true);
94108
when(this.context.getBean(anyString(), eq(Filter.class)))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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+
* 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 org.springframework.security.test.web.servlet.setup;
17+
18+
import org.junit.Test;
19+
import org.junit.runner.RunWith;
20+
import org.springframework.beans.factory.annotation.Autowired;
21+
import org.springframework.context.annotation.Configuration;
22+
import org.springframework.context.annotation.Import;
23+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
24+
import org.springframework.security.config.users.AuthenticationTestConfiguration;
25+
import org.springframework.test.context.junit4.SpringRunner;
26+
import org.springframework.test.context.web.WebAppConfiguration;
27+
import org.springframework.test.web.servlet.MockMvc;
28+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
29+
import org.springframework.web.context.WebApplicationContext;
30+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
31+
32+
import javax.servlet.Filter;
33+
34+
import static org.mockito.Mockito.mock;
35+
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
36+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
37+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
38+
39+
/**
40+
* @author Rob Winch
41+
*/
42+
@RunWith(SpringRunner.class)
43+
@WebAppConfiguration
44+
public class SecurityMockMvcConfigurersTests {
45+
@Autowired
46+
WebApplicationContext wac;
47+
48+
Filter noOpFilter = mock(Filter.class);
49+
50+
/**
51+
* Since noOpFilter is first does not continue the chain, security will not be invoked and the status should be OK
52+
*
53+
* @throws Exception
54+
*/
55+
@Test
56+
public void applySpringSecurityWhenAddFilterFirstThenFilterFirst() throws Exception {
57+
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
58+
.addFilters(this.noOpFilter)
59+
.apply(springSecurity())
60+
.build();
61+
62+
mockMvc.perform(get("/"))
63+
.andExpect(status().isOk());
64+
}
65+
66+
/**
67+
* Since noOpFilter is second security will be invoked and the status will be not OK. We know this because if noOpFilter
68+
* were first security would not be invoked sincet noOpFilter does not continue the FilterChain
69+
* @throws Exception
70+
*/
71+
@Test
72+
public void applySpringSecurityWhenAddFilterSecondThenSecurityFirst() throws Exception {
73+
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
74+
.apply(springSecurity())
75+
.addFilters(this.noOpFilter)
76+
.build();
77+
78+
mockMvc.perform(get("/"))
79+
.andExpect(status().is4xxClientError());
80+
}
81+
82+
@Configuration
83+
@EnableWebMvc
84+
@EnableWebSecurity
85+
@Import(AuthenticationTestConfiguration.class)
86+
static class Config {}
87+
}

0 commit comments

Comments
 (0)