解决Spring Security自定义filter重复执行问题
2024-09-03 15:25:08
今天做项目的时候,发现每次拦截器日志都会打两遍,很纳闷,怀疑是Filter被执行了两遍。结果debug之后发现还真是!记录一下这个神奇的BUG!
问题描述
项目中使用的是Spring-security作为权限框架,然后做了一个JwtAuthenticationTokenFilter
作为拦截器拦截请求,校验Token,但是每次请求都会打两遍日志。下面是精简的源代码:
自定义的Filter类
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
//...省略
//打出两遍日志的地方
log.info("User:{} request path:{}, method:{}, param:{}", username, request.getServletPath(),
request.getMethod(), request.getParameterMap() == null ? null : OBJECT_MAPPER.writeValueAsString(request.getParameterMap()));
//...省略
chain.doFilter(request, response);
}
}
WebSecurityConfig配置类
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//...省略
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//...省略
//把JwtAuthenticationTokenFilter加入到RememberMeAuthenticationFilter之前
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), RememberMeAuthenticationFilter.class);
}
//...省略
}
请求日志如下:
问题解决
把自定义FilterJwtAuthenticationTokenFilter
的@Component
取消掉就可以了,不让它被Spring容器管理。
原因
在spring容器托管的OncePerRequestFilter的bean,都会自动加入到servlet的filter chain,而上面的定义,还额外把filter加入到了spring security的
ememberMeAuthenticationFilter之前。而spring security也是一系列的filter,在mvc的filter之前执行。因此在鉴权通过的情况下,就会先后各执行一次。
参考资料
解决spring security自定义filter重复执行问题
最新文章
- QT5利用chromium内核与HTML页面交互
- Linux sed 批量替换多个文件中的字符串
- 如何让Ue4画面产生振动效果
- PIC32MZ tutorial -- Change Notification
- sql常识-INNER JOIN
- 如何用正则将多个空格看成一个空格结合spllit()方法将文本数据入库
- PHP系列笔记——Zend_Controller工作流程
- 安卓CTS官方文档之兼容性测试套件简介
- robin 今日南
- Request 地址栏传值
- fstream 学习
- 当yum安装出现Error: Package: glibc-headers .....时
- zabbix添加nginx监控
- VirtualBox安装CENTOS7.3常见问题
- MVC模块化开发方案
- PHP判断是否都是中文
- vue生成路由实例
- Teamwork(The seventh day of the team)
- 华为S5300系列交换机V100R005SPH020升级补丁
- HTML 页面中的 SVG