filterOne
仅适用于路径/1
,而filterTwo
仅适用于/2
。
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.antMatcher("/1")
.addFilterAfter(filterOneBean(), BasicAuthenticationFilter.class)
.authorizeRequests()
.and()
.antMatcher("/2")
.addFilterAfter(filterTwoBean(), BasicAuthenticationFilter.class)
.authorizeRequests()
.and();
/1
不会调用filterOne
或filterTwo
,而/2
仅调用filterOne
。为什么以及如何解决它?
编辑:以下配置仍会为filterOne
/2
@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MultiHttpSecurityConfig {
@Bean
public FilterTwo setFilterTwo() {
return new FilterTwo();
}
@Bean
public FilterOne setFilterOne() {
return new FilterOne();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private FilterTwo filterTwo;
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(filterTwo, BasicAuthenticationFilter.class)
.antMatcher("/2")
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
@Configuration
@Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private FilterOne filterOne;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(filterOne, BasicAuthenticationFilter.class)
.antMatcher("/1")
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
}
我可能会重申我想要实现的目标:/1
和/2
具有不同的身份验证规则,并且它们在自定义身份验证过滤器中实现,因此它们各自具有不同的过滤器链。
编辑2:我发现filterTwo
和一个filterChain
对象ID不同,这是因为setAuthentication
方法。
public class FilterTwo extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
...
SecurityContextHolder.getContext().setAuthentication(authentication); // This causes filterTwo invoked.
chain.doFilter(request,response);
}
}