Solve the problem of repeated execution of spring security custom filter.

  spring-security

Order

This article describes a problem that spring security customizes filter very easily, that is, filter is executed twice.

Reproduction

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public DemoFilter demoFilter(){
        return new DemoFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(demoFilter(),AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/login","/css/**", "/js/**","/fonts/**").permitAll()
                .anyRequest().authenticated();
    }
}

Where DemoFilter is as follows

public class DemoFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //do something
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

Reason

Bean of GenericFilterBean managed in spring container are automatically added to filter chain of servlet, and the above definition also adds filterchain to spring security’s
Before AnonymousAuthenticationFilter. Spring security is also a series of filters, executed before mvc’s filter. Therefore, when the authentication passes, it will be executed one after another.

Solution

Programme 1

Instead of hosting filter to spring, direct new, such as

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(new DemoFilter(),AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/login","/css/**", "/js/**","/fonts/**").permitAll()
                .anyRequest().authenticated();
    }
}

Option 2

Sometimes filter needs to access the resources of spring container, and it may be better to manage it to the container. then at this time, it can make a mark FILTER_APPLIED like FilterSecurityInterceptor.

public class DemoFilter extends GenericFilterBean {

    private static final String FILTER_APPLIED = "__spring_security_demoFilter_filterApplied";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest.getAttribute(FILTER_APPLIED) != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
        //do something
        servletRequest.setAttribute(FILTER_APPLIED,true);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

doc