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

Might be related to https://github.com/spring-projects/spring-boot/issues/1640

Comment From: rwinch

Please provide a complete sample that can be cloned from a github repository.

Comment From: puce77

@rwinch do you have a test security sample I can start with?

Comment From: rwinch

See https://github.com/rwinch/spring-security-sample/tree/gh-8428

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: rwinch

Thanks for the sample @puce77! It appears the issue is with Spring Boot. The problem is that the test does not use SecurityFilterAutoConfiguration which is what controls Spring Security's Filter ordering. Can you please create an issue with Spring Boot.

Comment From: puce77

As suggested I've filed an issue here: https://github.com/spring-projects/spring-boot/issues/21801