Skip to content

Commit a31a855

Browse files
committed
Fix HttpSecurity.addFilter* Ordering
Closes gh-9633
1 parent 2b4b856 commit a31a855

File tree

3 files changed

+196
-73
lines changed

3 files changed

+196
-73
lines changed

config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterComparator.java renamed to config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java

+3-59
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
package org.springframework.security.config.annotation.web.builders;
1818

19-
import java.io.Serializable;
2019
import java.util.Comparator;
2120
import java.util.HashMap;
2221
import java.util.Map;
@@ -47,7 +46,6 @@
4746
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
4847
import org.springframework.security.web.session.ConcurrentSessionFilter;
4948
import org.springframework.security.web.session.SessionManagementFilter;
50-
import org.springframework.util.Assert;
5149
import org.springframework.web.filter.CorsFilter;
5250

5351
/**
@@ -59,15 +57,15 @@
5957
*/
6058

6159
@SuppressWarnings("serial")
62-
final class FilterComparator implements Comparator<Filter>, Serializable {
60+
final class FilterOrderRegistration {
6361

6462
private static final int INITIAL_ORDER = 100;
6563

6664
private static final int ORDER_STEP = 100;
6765

6866
private final Map<String, Integer> filterToOrder = new HashMap<>();
6967

70-
FilterComparator() {
68+
FilterOrderRegistration() {
7169
Step order = new Step(INITIAL_ORDER, ORDER_STEP);
7270
put(ChannelProcessingFilter.class, order.next());
7371
order.next(); // gh-8105
@@ -116,60 +114,6 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
116114
put(SwitchUserFilter.class, order.next());
117115
}
118116

119-
@Override
120-
public int compare(Filter lhs, Filter rhs) {
121-
Integer left = getOrder(lhs.getClass());
122-
Integer right = getOrder(rhs.getClass());
123-
return left - right;
124-
}
125-
126-
/**
127-
* Determines if a particular {@link Filter} is registered to be sorted
128-
* @param filter
129-
* @return
130-
*/
131-
boolean isRegistered(Class<? extends Filter> filter) {
132-
return getOrder(filter) != null;
133-
}
134-
135-
/**
136-
* Registers a {@link Filter} to exist after a particular {@link Filter} that is
137-
* already registered.
138-
* @param filter the {@link Filter} to register
139-
* @param afterFilter the {@link Filter} that is already registered and that
140-
* {@code filter} should be placed after.
141-
*/
142-
void registerAfter(Class<? extends Filter> filter, Class<? extends Filter> afterFilter) {
143-
Integer position = getOrder(afterFilter);
144-
Assert.notNull(position, () -> "Cannot register after unregistered Filter " + afterFilter);
145-
put(filter, position + 1);
146-
}
147-
148-
/**
149-
* Registers a {@link Filter} to exist at a particular {@link Filter} position
150-
* @param filter the {@link Filter} to register
151-
* @param atFilter the {@link Filter} that is already registered and that
152-
* {@code filter} should be placed at.
153-
*/
154-
void registerAt(Class<? extends Filter> filter, Class<? extends Filter> atFilter) {
155-
Integer position = getOrder(atFilter);
156-
Assert.notNull(position, () -> "Cannot register after unregistered Filter " + atFilter);
157-
put(filter, position);
158-
}
159-
160-
/**
161-
* Registers a {@link Filter} to exist before a particular {@link Filter} that is
162-
* already registered.
163-
* @param filter the {@link Filter} to register
164-
* @param beforeFilter the {@link Filter} that is already registered and that
165-
* {@code filter} should be placed before.
166-
*/
167-
void registerBefore(Class<? extends Filter> filter, Class<? extends Filter> beforeFilter) {
168-
Integer position = getOrder(beforeFilter);
169-
Assert.notNull(position, () -> "Cannot register after unregistered Filter " + beforeFilter);
170-
put(filter, position - 1);
171-
}
172-
173117
private void put(Class<? extends Filter> filter, int position) {
174118
String className = filter.getName();
175119
this.filterToOrder.put(className, position);
@@ -181,7 +125,7 @@ private void put(Class<? extends Filter> filter, int position) {
181125
* @param clazz the {@link Filter} class to determine the sort order
182126
* @return the sort order or null if not defined
183127
*/
184-
private Integer getOrder(Class<?> clazz) {
128+
Integer getOrder(Class<?> clazz) {
185129
while (clazz != null) {
186130
Integer result = this.filterToOrder.get(clazz.getName());
187131
if (result != null) {

config/src/main/java/org/springframework/security/config/annotation/web/builders/HttpSecurity.java

+61-14
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@
1616

1717
package org.springframework.security.config.annotation.web.builders;
1818

19+
import java.io.IOException;
1920
import java.util.ArrayList;
2021
import java.util.List;
2122
import java.util.Map;
2223

2324
import javax.servlet.Filter;
25+
import javax.servlet.FilterChain;
26+
import javax.servlet.ServletException;
27+
import javax.servlet.ServletRequest;
28+
import javax.servlet.ServletResponse;
2429
import javax.servlet.http.HttpServletRequest;
2530

2631
import org.springframework.context.ApplicationContext;
32+
import org.springframework.core.OrderComparator;
33+
import org.springframework.core.Ordered;
2734
import org.springframework.http.HttpMethod;
2835
import org.springframework.security.authentication.AuthenticationManager;
2936
import org.springframework.security.authentication.AuthenticationProvider;
@@ -129,11 +136,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
129136

130137
private final RequestMatcherConfigurer requestMatcherConfigurer;
131138

132-
private List<Filter> filters = new ArrayList<>();
139+
private List<OrderedFilter> filters = new ArrayList<>();
133140

134141
private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE;
135142

136-
private FilterComparator comparator = new FilterComparator();
143+
private FilterOrderRegistration filterOrders = new FilterOrderRegistration();
137144

138145
/**
139146
* Creates a new instance
@@ -2609,8 +2616,12 @@ protected void beforeConfigure() throws Exception {
26092616

26102617
@Override
26112618
protected DefaultSecurityFilterChain performBuild() {
2612-
this.filters.sort(this.comparator);
2613-
return new DefaultSecurityFilterChain(this.requestMatcher, this.filters);
2619+
this.filters.sort(OrderComparator.INSTANCE);
2620+
List<Filter> sortedFilters = new ArrayList<>(this.filters.size());
2621+
for (Filter filter : this.filters) {
2622+
sortedFilters.add(((OrderedFilter) filter).filter);
2623+
}
2624+
return new DefaultSecurityFilterChain(this.requestMatcher, sortedFilters);
26142625
}
26152626

26162627
@Override
@@ -2631,24 +2642,28 @@ private AuthenticationManagerBuilder getAuthenticationRegistry() {
26312642

26322643
@Override
26332644
public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {
2634-
this.comparator.registerAfter(filter.getClass(), afterFilter);
2635-
return addFilter(filter);
2645+
return addFilterAtOffsetOf(filter, 1, afterFilter);
26362646
}
26372647

26382648
@Override
26392649
public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) {
2640-
this.comparator.registerBefore(filter.getClass(), beforeFilter);
2641-
return addFilter(filter);
2650+
return addFilterAtOffsetOf(filter, -1, beforeFilter);
2651+
}
2652+
2653+
private HttpSecurity addFilterAtOffsetOf(Filter filter, int offset, Class<? extends Filter> registeredFilter) {
2654+
int order = this.filterOrders.getOrder(registeredFilter) + offset;
2655+
this.filters.add(new OrderedFilter(filter, order));
2656+
return this;
26422657
}
26432658

26442659
@Override
26452660
public HttpSecurity addFilter(Filter filter) {
2646-
Class<? extends Filter> filterClass = filter.getClass();
2647-
if (!this.comparator.isRegistered(filterClass)) {
2648-
throw new IllegalArgumentException("The Filter class " + filterClass.getName()
2661+
Integer order = this.filterOrders.getOrder(filter.getClass());
2662+
if (order == null) {
2663+
throw new IllegalArgumentException("The Filter class " + filter.getClass().getName()
26492664
+ " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
26502665
}
2651-
this.filters.add(filter);
2666+
this.filters.add(new OrderedFilter(filter, order));
26522667
return this;
26532668
}
26542669

@@ -2671,8 +2686,7 @@ public HttpSecurity addFilter(Filter filter) {
26712686
* @return the {@link HttpSecurity} for further customizations
26722687
*/
26732688
public HttpSecurity addFilterAt(Filter filter, Class<? extends Filter> atFilter) {
2674-
this.comparator.registerAt(filter.getClass(), atFilter);
2675-
return addFilter(filter);
2689+
return addFilterAtOffsetOf(filter, 0, atFilter);
26762690
}
26772691

26782692
/**
@@ -3060,4 +3074,37 @@ public HttpSecurity and() {
30603074

30613075
}
30623076

3077+
/**
3078+
* A Filter that implements Ordered to be sorted. After sorting occurs, the original
3079+
* filter is what is used by FilterChainProxy
3080+
*/
3081+
private static final class OrderedFilter implements Ordered, Filter {
3082+
3083+
private final Filter filter;
3084+
3085+
private final int order;
3086+
3087+
private OrderedFilter(Filter filter, int order) {
3088+
this.filter = filter;
3089+
this.order = order;
3090+
}
3091+
3092+
@Override
3093+
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
3094+
throws IOException, ServletException {
3095+
this.filter.doFilter(servletRequest, servletResponse, filterChain);
3096+
}
3097+
3098+
@Override
3099+
public int getOrder() {
3100+
return this.order;
3101+
}
3102+
3103+
@Override
3104+
public String toString() {
3105+
return "OrderedFilter{" + "filter=" + this.filter + ", order=" + this.order + '}';
3106+
}
3107+
3108+
}
3109+
30633110
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/*
2+
* Copyright 2002-2020 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.security.config.annotation.web.builders;
18+
19+
import java.io.IOException;
20+
import java.util.List;
21+
import java.util.stream.Collectors;
22+
23+
import javax.servlet.Filter;
24+
import javax.servlet.FilterChain;
25+
import javax.servlet.ServletException;
26+
import javax.servlet.ServletRequest;
27+
import javax.servlet.ServletResponse;
28+
29+
import org.assertj.core.api.ListAssert;
30+
import org.junit.Rule;
31+
import org.junit.Test;
32+
33+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
34+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
35+
import org.springframework.security.config.test.SpringTestRule;
36+
import org.springframework.security.web.FilterChainProxy;
37+
import org.springframework.security.web.access.ExceptionTranslationFilter;
38+
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
39+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
40+
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
41+
42+
import static org.assertj.core.api.Assertions.assertThat;
43+
44+
public class HttpSecurityAddFilterTest {
45+
46+
@Rule
47+
public final SpringTestRule spring = new SpringTestRule();
48+
49+
@Test
50+
public void addFilterAfterWhenSameFilterDifferentPlacesThenOrderCorrect() {
51+
this.spring.register(MyFilterMultipleAfterConfig.class).autowire();
52+
53+
assertThatFilters().containsSubsequence(WebAsyncManagerIntegrationFilter.class, MyFilter.class,
54+
ExceptionTranslationFilter.class, MyFilter.class);
55+
}
56+
57+
@Test
58+
public void addFilterBeforeWhenSameFilterDifferentPlacesThenOrderCorrect() {
59+
this.spring.register(MyFilterMultipleBeforeConfig.class).autowire();
60+
61+
assertThatFilters().containsSubsequence(MyFilter.class, WebAsyncManagerIntegrationFilter.class, MyFilter.class,
62+
ExceptionTranslationFilter.class);
63+
}
64+
65+
@Test
66+
public void addFilterAtWhenSameFilterDifferentPlacesThenOrderCorrect() {
67+
this.spring.register(MyFilterMultipleAtConfig.class).autowire();
68+
69+
assertThatFilters().containsSubsequence(MyFilter.class, WebAsyncManagerIntegrationFilter.class, MyFilter.class,
70+
ExceptionTranslationFilter.class);
71+
}
72+
73+
private ListAssert<Class<?>> assertThatFilters() {
74+
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
75+
List<Class<?>> filters = filterChain.getFilters("/").stream().map(Object::getClass)
76+
.collect(Collectors.toList());
77+
return assertThat(filters);
78+
}
79+
80+
public static class MyFilter implements Filter {
81+
82+
@Override
83+
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
84+
throws IOException, ServletException {
85+
filterChain.doFilter(servletRequest, servletResponse);
86+
}
87+
88+
}
89+
90+
@EnableWebSecurity
91+
static class MyFilterMultipleAfterConfig extends WebSecurityConfigurerAdapter {
92+
93+
@Override
94+
protected void configure(HttpSecurity http) throws Exception {
95+
// @formatter:off
96+
http
97+
.addFilterAfter(new MyFilter(), WebAsyncManagerIntegrationFilter.class)
98+
.addFilterAfter(new MyFilter(), ExceptionTranslationFilter.class);
99+
// @formatter:on
100+
}
101+
102+
}
103+
104+
@EnableWebSecurity
105+
static class MyFilterMultipleBeforeConfig extends WebSecurityConfigurerAdapter {
106+
107+
@Override
108+
protected void configure(HttpSecurity http) throws Exception {
109+
// @formatter:off
110+
http
111+
.addFilterBefore(new MyFilter(), WebAsyncManagerIntegrationFilter.class)
112+
.addFilterBefore(new MyFilter(), ExceptionTranslationFilter.class);
113+
// @formatter:on
114+
}
115+
116+
}
117+
118+
@EnableWebSecurity
119+
static class MyFilterMultipleAtConfig extends WebSecurityConfigurerAdapter {
120+
121+
@Override
122+
protected void configure(HttpSecurity http) throws Exception {
123+
// @formatter:off
124+
http
125+
.addFilterAt(new MyFilter(), ChannelProcessingFilter.class)
126+
.addFilterAt(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
127+
// @formatter:on
128+
}
129+
130+
}
131+
132+
}

0 commit comments

Comments
 (0)