Running code before SpringSecurityFilterChain was a problem we faced while implementing a huge project in Spring. For example, our logger filter would not log security redirections (like redirecting to auth/login). After a little digging, I found out following bean registration code:

    @Bean
    public FilterRegistrationBean registerCorsFilter(CORSFilter filter) {
        FilterRegistrationBean reg = new FilterRegistrationBean(filter);
        reg.setOrder(4);
        return reg;
    }

This method, when inserted in the configuration class (which is annotated with @Configuration), defines the order in which filters will run. But, we couldn't register SpringSecurityFilterChain like this, because a similar order was defined in this commit to the framework. As stated in the commit, we can change the order in application.properties file easily:

security.filter-order=5

After this simple configuration, filters which have order up to 5 run before SpringSecurityFilterChain:


    @Bean
    public FilterRegistrationBean registerRequestLogFilter(RequestLogFilter filter) {
        FilterRegistrationBean reg = new FilterRegistrationBean(filter);
        reg.setOrder(3);
        return reg;
    }

    @Bean
    public FilterRegistrationBean registerCorsFilter(CORSFilter filter) {
        FilterRegistrationBean reg = new FilterRegistrationBean(filter);
        reg.setOrder(4);
        return reg;
    }