Conflict between Spring Security and Custom filter Leads to Multi Execution Solution

  • 2021-10-11 18:16:00
  • OfStack

Problem description:

When using Spring Security, it is necessary to inject filter object of Security through @ bean annotation in WebSecurityConfig, but I don't know whether it is because of spring boot framework or some unknown reason, which leads to injection here, and this object will be injected once more, resulting in returning to this filter for another execution after the filter chain is finished.


@Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationTokenFilter();
    }

This is the object that needs to be injected in WebSecurityConfig. java.


httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

Add to Security, at this time, it may cause filter chain to execute filter added to Security again after it should have been executed...

Solution:

Commenting these two code segments can be solved. Of course, it only solves the problem of executing filter of Security after the execution of filter chain, which cannot really solve the problem in essence. If there is a better understanding or a better solution, please discuss it.

2019-5-9 16: 49: 00: I found out before doing this, In this way, Spring Security is equivalent to no effect. However, filter will still work, and if Spring Security is enabled, it will still enter filter... If you authorize customization, Spring Security feels useless. Of course, this is the problem I encountered, and the framework was built by others, but the usage is wrong, which leads to the written filter becoming customized. It feels incompatible with Spring Security framework. If there are big brothers who know, welcome guidance! Thank you

If you want to use Spring Security, you need to delete or comment out the @ Component annotation on JwtAuthenticationTokenFilter, because this is the class injected twice, but the generated class object should be different, which will lead to entering filter twice.

So now I doubt whether Spring Security is necessary...

Spring Security3 Custom Security Filter Location and Precautions

When auto-config= "true", springSecurity automatically creates a filter chain

1. The custom filter position needs to be before or after the existing filter, otherwise an error will be reported;

2. Since FilterSecurityInterceptor is secure, observeOncePerRequest (1 per request) defaults to true.

By default, FilterSecurityInterceptor only executes one, so if you want to execute both the default security filter and the custom filter, put the custom filter before the default security filter and set false to false.

Such as:

(1)


<custom-filter after="FILTER_SECURITY_INTERCEPTOR" ref="menuFilter" />

(2)


<beans:property name="observeOncePerRequest" value="false" />

Related articles: