The filter is called twice when registering as a Spring bean

I want to use @Autowirewith Filter. Therefore, I define my filter in SecurityConfigas shown below:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(getA(), BasicAuthenticationFilter.class);
        http.csrf().disable();
    }

    @Bean
    public A getA(){
        return new A();
    }

This filter Aextends Spring GenericFilterBean.

I get the below output when I call the controller, which shows that the filter hits twice.

filter A before
filter A before
mycontroller invoke
filter A after
filter A after

My observation is the following call with the Spring container, because if the filter is not registered as a bean, it receives only once. What is the reason and how to fix it?

+4
source share
1 answer

, Spring Boot bean, Filter . , bean Spring .

, bean. , Spring Boot . , FilterRegistrationBean:

@Bean
public FilterRegistrationBean registration(MyFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(false);
    return registration;
}
+11

Source: https://habr.com/ru/post/1653562/


All Articles