Skip to content

Commit 26788a7

Browse files
committed
Fix HttpSecurity.addFilter* Ordering
Closes gh-9633
1 parent 67d5520 commit 26788a7

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;
@@ -46,7 +45,6 @@
4645
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
4746
import org.springframework.security.web.session.ConcurrentSessionFilter;
4847
import org.springframework.security.web.session.SessionManagementFilter;
49-
import org.springframework.util.Assert;
5048
import org.springframework.web.filter.CorsFilter;
5149

5250
/**
@@ -58,15 +56,15 @@
5856
*/
5957

6058
@SuppressWarnings("serial")
61-
final class FilterComparator implements Comparator<Filter>, Serializable {
59+
final class FilterOrderRegistration {
6260

6361
private static final int INITIAL_ORDER = 100;
6462

6563
private static final int ORDER_STEP = 100;
6664

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

69-
FilterComparator() {
67+
FilterOrderRegistration() {
7068
Step order = new Step(INITIAL_ORDER, ORDER_STEP);
7169
put(ChannelProcessingFilter.class, order.next());
7270
order.next(); // gh-8105
@@ -114,60 +112,6 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
114112
put(SwitchUserFilter.class, order.next());
115113
}
116114

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

128135
private final RequestMatcherConfigurer requestMatcherConfigurer;
129136

130-
private List<Filter> filters = new ArrayList<>();
137+
private List<OrderedFilter> filters = new ArrayList<>();
131138

132139
private RequestMatcher requestMatcher = AnyRequestMatcher.INSTANCE;
133140

134-
private FilterComparator comparator = new FilterComparator();
141+
private FilterOrderRegistration filterOrders = new FilterOrderRegistration();
135142

136143
/**
137144
* Creates a new instance
@@ -2522,8 +2529,12 @@ protected void beforeConfigure() throws Exception {
25222529

25232530
@Override
25242531
protected DefaultSecurityFilterChain performBuild() {
2525-
this.filters.sort(this.comparator);
2526-
return new DefaultSecurityFilterChain(this.requestMatcher, this.filters);
2532+
this.filters.sort(OrderComparator.INSTANCE);
2533+
List<Filter> sortedFilters = new ArrayList<>(this.filters.size());
2534+
for (Filter filter : this.filters) {
2535+
sortedFilters.add(((OrderedFilter) filter).filter);
2536+
}
2537+
return new DefaultSecurityFilterChain(this.requestMatcher, sortedFilters);
25272538
}
25282539

25292540
@Override
@@ -2544,24 +2555,28 @@ private AuthenticationManagerBuilder getAuthenticationRegistry() {
25442555

25452556
@Override
25462557
public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {
2547-
this.comparator.registerAfter(filter.getClass(), afterFilter);
2548-
return addFilter(filter);
2558+
return addFilterAtOffsetOf(filter, 1, afterFilter);
25492559
}
25502560

25512561
@Override
25522562
public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) {
2553-
this.comparator.registerBefore(filter.getClass(), beforeFilter);
2554-
return addFilter(filter);
2563+
return addFilterAtOffsetOf(filter, -1, beforeFilter);
2564+
}
2565+
2566+
private HttpSecurity addFilterAtOffsetOf(Filter filter, int offset, Class<? extends Filter> registeredFilter) {
2567+
int order = this.filterOrders.getOrder(registeredFilter) + offset;
2568+
this.filters.add(new OrderedFilter(filter, order));
2569+
return this;
25552570
}
25562571

25572572
@Override
25582573
public HttpSecurity addFilter(Filter filter) {
2559-
Class<? extends Filter> filterClass = filter.getClass();
2560-
if (!this.comparator.isRegistered(filterClass)) {
2561-
throw new IllegalArgumentException("The Filter class " + filterClass.getName()
2574+
Integer order = this.filterOrders.getOrder(filter.getClass());
2575+
if (order == null) {
2576+
throw new IllegalArgumentException("The Filter class " + filter.getClass().getName()
25622577
+ " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
25632578
}
2564-
this.filters.add(filter);
2579+
this.filters.add(new OrderedFilter(filter, order));
25652580
return this;
25662581
}
25672582

@@ -2584,8 +2599,7 @@ public HttpSecurity addFilter(Filter filter) {
25842599
* @return the {@link HttpSecurity} for further customizations
25852600
*/
25862601
public HttpSecurity addFilterAt(Filter filter, Class<? extends Filter> atFilter) {
2587-
this.comparator.registerAt(filter.getClass(), atFilter);
2588-
return addFilter(filter);
2602+
return addFilterAtOffsetOf(filter, 0, atFilter);
25892603
}
25902604

25912605
/**
@@ -2973,4 +2987,37 @@ public HttpSecurity and() {
29732987

29742988
}
29752989

2990+
/**
2991+
* A Filter that implements Ordered to be sorted. After sorting occurs, the original
2992+
* filter is what is used by FilterChainProxy
2993+
*/
2994+
private static final class OrderedFilter implements Ordered, Filter {
2995+
2996+
private final Filter filter;
2997+
2998+
private final int order;
2999+
3000+
private OrderedFilter(Filter filter, int order) {
3001+
this.filter = filter;
3002+
this.order = order;
3003+
}
3004+
3005+
@Override
3006+
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
3007+
throws IOException, ServletException {
3008+
this.filter.doFilter(servletRequest, servletResponse, filterChain);
3009+
}
3010+
3011+
@Override
3012+
public int getOrder() {
3013+
return this.order;
3014+
}
3015+
3016+
@Override
3017+
public String toString() {
3018+
return "OrderedFilter{" + "filter=" + this.filter + ", order=" + this.order + '}';
3019+
}
3020+
3021+
}
3022+
29763023
}
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)