Describe the bug WebMvcTests with spring-security-test have a different filter order than during "normal" runtime.

To Reproduce Define a filter after the default order of Spring Security Filters (=0) and try to access the userPrincipal from the HttpServletRequest:

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
@Order(TestFilter.ORDER)
public class TestFilter extends OncePerRequestFilter {

    public static final int ORDER = Ordered.LOWEST_PRECEDENCE - 10; // - 10 to allow applications/ libraries to register filters after this one

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Assert.notNull(request.getUserPrincipal(), "userPrincipal");

        filterChain.doFilter(request, response);
    }
}

Expected behavior Same filter order during tests as during runtime.

Comment From: puce77

Issue originally reported at: https://github.com/spring-projects/spring-security/issues/8428 It seems to be a Spring Boot issue, though.

Comment From: puce77

Here is a sample: 8428-spring-security-test-v1.0.zip (from: https://github.com/puce77/spring-security-sample/tree/8428-spring-security-test )

If Assert.notNull(request.getUserPrincipal(), "userPrincipal"); is commented out in the filter, the tests run fine, but with this null check the tests fail, though the REST service runs fine.

Comment From: wilkinsona

Thanks for the sample, @puce77. You can work around the problem by adding @ImportAutoConfiguration(SecurityFilterAutoConfiguration.class) to your test class:

@WebMvcTest(controllers = SecuredEchoController.class)
@ExtendWith(SpringExtension.class)
@ImportAutoConfiguration(SecurityFilterAutoConfiguration.class)
public class SecuredEchoControllerTest {

Completely unrelated to your problem, you can remove @ExtendWith(SpringExtension.class) as @WebMvcTest does that for you:

@WebMvcTest(controllers = SecuredEchoController.class)
@ImportAutoConfiguration(SecurityFilterAutoConfiguration.class)
public class SecuredEchoControllerTest {

Comment From: puce77

First tests with work-around were successful, thanks!