我想禁用安全链中的一个Spring Security过滤器。
我已经看到了Prevent Spring Boot from registering a servlet filter问题 - 并且接受了应该有效,但遗憾的是不是。
使用代码:
@Bean
public FilterRegistrationBean registration(AnonymousAuthenticationFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
Spring Boot会立即宣布没有合格的bean,这很难过:
由以下原因引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[org.springframework.security.web.authentication.AnonymousAuthenticationFilter]的符合条件的bean依赖:预期至少有1个bean有资格作为autowire候选者依赖。依赖注释:{}
创建另一个bean之后:
@SuppressWarnings("deprecation") // Oh, there be dragons
@Bean
public AnonymousAuthenticationFilter anonymousAuthenticationFilter() {
return new AnonymousAuthenticationFilter();
}
我受到攻击
引起:java.lang.IllegalArgumentException:[断言失败] - 此String参数必须具有长度;它不能为空或空
完全明白; Assert
方法https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.java中的afterPropertiesSet()
阻止我使用默认构造函数。使用另一种方法:
@Bean
public AnonymousAuthenticationFilter anonymousAuthenticationFilter() {
// it will be disabled anyway so...
return new AnonymousAuthenticationFilter("_", new Object(), new ArrayList<GrantedAuthority>());
}
一切都更好:
INFO 4916 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean:过滤anonymousAuthenticationFilter未注册(禁用)
DEBUG 4916 --- [ost-startStop-1] o.s.security.web.FilterChainProxy:初始化过滤器&#39; springSecurityFilterChain&#39;
DEBUG 4916 --- [ost-startStop-1] o.s.security.web.FilterChainProxy:Filter&#39; springSecurityFilterChain&#39;已成功配置
但在获得一些资源后我得到了:
DEBUG 4916 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy:/用户位于第10位的13位额外过滤链;触发过滤器:&#39; AnonymousAuthenticationFilter&#39;
DEBUG 4916 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter:带有匿名令牌的填充SecurityContextHolder:&#39; org.springframework.security.authentication.AnonymousAuthenticationToken@90572420:Principal:anonymousUser;证书:[保护];认证:真实;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@255f8:RemoteIpAddress:127.0.0.1; SessionId:6B9D974A4634548750FE78C18F62A6B0;授权机构:ROLE_ANONYMOUS&#39;
由于某些原因,AnonymousAuthenticationFilter仍然有效。 问题:是否有办法在Spring Boot应用程序中禁用此类过滤器?
答案 0 :(得分:31)
Spring Security bundles all of the Filters within the HttpSecurity
configuration. To disable anonymous authentication use the following:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.anonymous().disable()
...
}
...
}
If you want to disable all of the defaults within Spring Security you can pass true into the parent class constructor to disable defaults. For example:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
public SecurityConfig() {
super(true);
}
...
}