提问者:小点点

SpringwebSecurity.ignoring()不忽略自定义过滤器


我在Spring 4 MVC Security Boot项目中设置了一个自定义身份验证过滤器。过滤器工作正常,现在我想禁用某些URI的安全性(如/api/**)。这是我的配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity.ignoring().antMatchers("/api/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
                 .anyRequest().authenticated()
              .and()
                 .addFilterBefore(filter, BasicAuthenticationFilter.class);
    }
}

不幸的是,当我在/api/...下调用资源时,过滤器仍然是链接的。我在过滤器中添加了println,并且每次调用都会将其写入控制台。你知道我的配置有什么问题吗?

更新

过滤代码:

@Component
public class EAccessAuthenticationFilter extends RequestHeaderAuthenticationFilter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("FILTER");
        if(SecurityContextHolder.getContext().getAuthentication() == null){
            //Do my authentication stuff
            PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(user, credential, authorities);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }  
        super.doFilter(request, response, chain);
     }

    @Override
    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

}

共3个答案

匿名用户

删除EAccessAuthenticationFilter类上的@Component,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
             .anyRequest().authenticated()
          .and()
             .addFilterBefore(new EAccessAuthenticationFilter(), BasicAuthenticationFilter.class);
}

https://github.com/spring-projects/spring-security/issues/3958

匿名用户

我没有足够的声誉来添加评论,但对于像我这样正在寻找对kimhom的答案进行更多解释的人来说,WebSecurityConfigurerAdapter会告诉Spring Security忽略通过它添加的任何过滤器。过滤器仍然被调用,因为@Component或任何@Bean)注释告诉Spring(再次)在安全链之外添加过滤器。因此,虽然过滤器在安全链中被忽略,但它并没有被另一个(非安全?)链忽略。

这为我解决了两周的头痛。在我的情况下,我的自定义过滤器需要SecurityContext给出的身份验证对象,它一直显示为空,因为安全链从未执行过。

匿名用户

我有正确的配置来忽略Web安全配置中的某些上下文路径,如下所示。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v1/api1").antMatchers("/v1/api2");
}

但是我错误地在我的控制器方法上添加了@PreAuthorize(...),似乎该方法级安全性覆盖了开始时设置的任何安全配置。