问题
I have 2 Spring Security WebSecurityConfigurerAdapter
configs. I want to filter all requests to path /filter1
with filter 1, excluding /filter1/filter2
path. The latter one I want to filter with filter 2. How can I achieve it?
Filter 1 config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("filter1/filter2/**").permitAll()
.and()
.antMatcher("filter1/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(filter1, FilterSecurityInterceptor.class);
}
Filter 2 config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.antMatcher("filter1/filter2/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(filter2, FilterSecurityInterceptor.class);
}
回答1:
Just write a single configuration, ordering the urls in the way they should match (ordering is important here!).
Something like the following
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.antMatcher("filter1/filter2/**")
.addFilterBefore(filter2, FilterSecurityInterceptor.class)
.antMatcher("filter1/**")
.addFilterBefore(filter1, FilterSecurityInterceptor.class);
Should do that. It will match the most specific one and use that filter chain. Not sure if you need to move the .authorizeRequests().anyRequest().authenticated()
to each mapping as well.
来源:https://stackoverflow.com/questions/53238234/multiple-spring-security-filters