Spring security custom filter called multiple times

If you are using Spring Boot, any GenericFilterBean (OncePerRequestFilter is one) in the context will be automatically added to the filter chain. Meaning the configuration you have above will include the same filter twice.

The easiest workaround for this is to define a FilterRegistrationBean in the context, and have it disabled:

<beans:bean id="customLogoutFilterRegistration" class="org.springframework.boot.context.embedded.FilterRegistrationBean">
    <beans:property name="filter" ref="customLogoutFilter"/>
    <beans:property name="enabled" value="false"/>
</beans:bean>

EDIT (11/3/2020):

For anyone working in SpringBoot and wanting to register the bean using annotations. Add the following code in the Spring Boot app initializer file (one with @SpringBootApplication annotation):

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new YourCustomFilterClassName());
    registrationBean.setEnabled(false);
    return registrationBean;
}

Just sharing my case :(

I wasn't setting authentication.setAuthenticated(true) in the AuthenticationProvider.

Hence, AbstractPreAuthenticatedProcessingFilter called authenticate once, then AbstractSecurityInterceptor was also calling authenticateIfNeeded.


It is likely being called for other URLs that are being requested. For example, if you have any css, javascript, images that are loaded on the page it will be called for each of those. Try adding a logging statement that displays the current request information to find out if that is the case. For example,

logger.error("URL = " + req.getRequestURL());