Double Filter Invocations in Spring Bean Filter Registrations
When working with Spring Security, registering a filter as a bean may result in unintentional double invocations. This occurs when Spring's autowiring mechanism registers the filter twice: once through the conventional bean discovery process and again due to the filter's subclassing of Spring's GenericFilterBean.
Cause of the Problem:
The culprit is the automatic registration of filters as beans by Spring Boot. This is intended to simplify filter configuration but can lead to redundancies when filters are explicitly defined and registered with Spring Security.
Fix:
To resolve this issue, you must explicitly inform Spring Boot not to register your filter as a bean. This can be achieved using the FilterRegistrationBean, as per the Spring documentation:
@Bean public FilterRegistrationBean<MyFilter> registration(MyFilter filter) { FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>(filter); registration.setEnabled(false); return registration; }
By disabling registration via setEnabled(false), you effectively prevent Spring Boot from automatically registering the filter. However, your filter will still be recognized and applied by Spring Security due to its registration in the configure method.
The above is the detailed content of Why Are My Spring Security Filters Invoked Twice?. For more information, please follow other related articles on the PHP Chinese website!