Spring webSecurity.ignoring() 不会忽略自定义过滤器 [英] Spring webSecurity.ignoring() doesn't ignore custom filter
问题描述
我在 Spring 4 MVC + Security + Boot 项目中设置了自定义身份验证过滤器.过滤器做得很好,现在我想禁用某些 URI(如 /api/**
)的安全性.这是我的配置:
I have a set a custom authentication filter in my Spring 4 MVC + Security + Boot project. The filter does it's job well and now I want to disable the security for some URI (like /api/**
). Here is my configuration:
@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
并且在每次调用时都会将其写入控制台.你知道我的配置有什么问题吗?
Unfortunately, when I call a resource under /api/...
the filter is still chained. I've added println
in my filter and it's written to the console on every call. Do you know what's wrong with my configuration?
更新
过滤代码:
@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);
}
}
推荐答案
删除类 EAccessAuthenticationFilter 上的@Component,像这样:
remove @Component on class EAccessAuthenticationFilter,and like this:
@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/问题/3958
这篇关于Spring webSecurity.ignoring() 不会忽略自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!