【发布时间】:2017-02-03 14:19:27
【问题描述】:
我正在尝试使用两个不同的过滤器配置 Spring Security。 我想要的是有一些将由一个过滤器处理的 URL,以及一些将由其他过滤器处理的 URL。 这是我想出的设置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled=true)
public class SecurityConfigurationContext {
@Order(1)
@Configuration
public static class ConfigurerAdapter1 extends WebSecurityConfigurerAdapter{
...
@Override
protected void configure(final HttpSecurity http) throws Exception {
// Handlers and entry points
http.exceptionHandling()
.authenticationEntryPoint(MyCustomAuthenticationEntryPoint);
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/filter1-urls/*").hasRole("USER");
http.addFilterBefore(myCustomFilter1, ChannelProcessingFilter.class);
http.csrf().disable();
http.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myCustomAuthenticationService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
@Order(2)
@Configuration
public static class ConfigurerAdapter2 extends WebSecurityConfigurerAdapter{
...
@Override
protected void configure(final HttpSecurity http) throws Exception {
// Handlers and entry points
http.exceptionHandling()
.authenticationEntryPoint(MyCustomAuthenticationEntryPoint);
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/filter2-urls/*").hasRole("SUPER_USER");
http.addFilterBefore(myCustomFilter2, ChannelProcessingFilter.class);
http.csrf().disable();
http.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myCustomAuthenticationService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
}
过滤器看起来像这样:
过滤器1:
@Component
@Order(1)
public final class MyCustomFilter1 implements Filter{
public MyCustomFilter1() {
super();
}
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
// logic for processing filter1-urls
}
}
过滤器2:
@Component
@Order(2)
public final class MyCustomFilter2 implements Filter{
public MyCustomFilter2() {
super();
}
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
// logic for processing filter2-urls
}
}
问题在于,对于每个请求,这两个过滤器都在一个链中调用。我提出的任何请求,它首先通过一个过滤器,然后通过另一个,而不是只通过一个。
我该如何解决这个问题?
提前致谢。
【问题讨论】: