【发布时间】:2021-01-22 06:18:58
【问题描述】:
我实现了一个 customFilter,它将请求的 cookie 中的某些内容添加到其标头中:
@Component
@Slf4j
public class MyCustomFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
.... some logic...
log.info("Sending request to next chain for validation..");
chain.doFilter(request, response);
log.info("Authentication completed sucessfully");
}
@Bean
// This method is needed to replace the default cookieFilter.json processor of tomcat that ignores the jwt cookieFilter.json
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return tomcatServletWebServerFactory -> tomcatServletWebServerFactory.addContextCustomizers((TomcatContextCustomizer) context -> {
context.setCookieProcessor(new LegacyCookieProcessor());
});
}
}
我的 WebSecurityConfigurerAdapter 类:
@Configuration
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//configuring strategy
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt().and();
http.csrf().disable();
http.addFilterBefore(new MyCustomFilter (), UsernamePasswordAuthenticationFilter.class);
http.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint());
}
}
当我运行代码并通过邮递员/curl 发送请求时,我看到过滤器在
Sending request to next chain for validation..
Sending request to next chain for validation..
Authentication completed sucessfully
Authentication completed sucessfully
我发现了一些关于问题的帖子,并尝试了以下解决方案:
-
这是因为 spring 自动注册了 beans,我在 configure 方法中手动添加了过滤器。因此,我删除了 configure() 方法中手动添加的过滤器。结果是过滤器根本没有被调用。
-
尝试扩展
OncePerRequestFilter类,而不是实现过滤器接口。这样做了,但过滤器仍然触发了两次。 -
还尝试删除
@Component注释并手动添加过滤器。此外,我必须将CookieProcessorbean 移动到 Configuration 类。之后出现的问题是应用无法启动,原因如下:原因:org.springframework.beans.BeanInstantiationException:无法实例化[org.springframework.web.servlet.HandlerMapping]:工厂方法'resourceHandlerMapping'抛出异常;嵌套异常是 java.lang.IllegalStateException: No ServletContext set
我使用的是 spring-security 版本 5.3.3。
【问题讨论】:
-
删除
@Component。它目前是普通过滤器链和安全过滤器链的一部分,因此它被执行了两次(它也被注册了两次)。@Bean方法应该在@Configuration类上,而不是在@Component上。 -
我将 bean 移动到配置中,但出现以下错误: 原因:org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.web.servlet.HandlerMapping]:工厂方法“resourceHandlerMapping”抛出异常;嵌套异常是 java.lang.IllegalStateException: No ServletContext set
-
返回
TomcatContextCustomizer并且不要添加它。你把事情弄得太复杂了。 -
我使用了以下代码,但仍然出现相同的错误: public TomcatContextCustomizer cookieProcessorCustomizer() { return context -> context.setCookieProcessor(new LegacyCookieProcessor()); }
标签: java spring spring-boot spring-security