Home > Java > javaTutorial > Why Are My Spring Security Filters Invoked Twice?

Why Are My Spring Security Filters Invoked Twice?

Patricia Arquette
Release: 2024-12-25 01:43:13
Original
420 people have browsed it

Why Are My Spring Security Filters Invoked Twice?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template