Fix WebTestUtils when no matching HttpSecurity found

Previously a NullPointerException would be thrown if no HttpSecurity
matched on the request passed in. This was because findFilters would
return null rather than an empty List.

This commit returns null if findFilters gets a null result.

Fixes gh-3343
This commit is contained in:
Rob Winch 2016-03-09 15:20:10 -06:00
parent dd8ba8c07e
commit 618b8a2d83
2 changed files with 27 additions and 1 deletions

View File

@ -114,7 +114,7 @@ public abstract class WebTestUtils {
}
@SuppressWarnings("unchecked")
private static <T extends Filter> T findFilter(HttpServletRequest request,
static <T extends Filter> T findFilter(HttpServletRequest request,
Class<T> filterClass) {
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getWebApplicationContext(request.getServletContext());
@ -131,6 +131,9 @@ public abstract class WebTestUtils {
}
List<Filter> filters = (List<Filter>) ReflectionTestUtils.invokeMethod(
springSecurityFilterChain, "getFilters", request);
if(filters == null) {
return null;
}
for (Filter filter : filters) {
if (filterClass.isAssignableFrom(filter.getClass())) {
return (T) filter;

View File

@ -32,6 +32,7 @@ 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.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
@ -118,6 +119,14 @@ public class WebTestUtilsTests {
assertThat(getSecurityContextRepository(request)).isSameAs(contextRepo);
}
// gh-3343
@Test
public void findFilterNoMatchingFilters() {
loadConfig(PartialSecurityConfig.class);
assertThat(WebTestUtils.findFilter(request, SecurityContextPersistenceFilter.class)).isNull();
}
private void loadConfig(Class<?> config) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(config);
@ -157,4 +166,18 @@ public class WebTestUtilsTests {
}
// @formatter:on
}
@EnableWebSecurity
static class PartialSecurityConfig extends WebSecurityConfigurerAdapter {
// @formatter:off
@Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/willnotmatchthis");
}
// @formatter:on
}
}