今天做项目的时候,发现每次拦截器日志都会打两遍,很纳闷,怀疑是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重复执行问题

最新文章

  1. QT5利用chromium内核与HTML页面交互
  2. Linux sed 批量替换多个文件中的字符串
  3. 如何让Ue4画面产生振动效果
  4. PIC32MZ tutorial -- Change Notification
  5. sql常识-INNER JOIN
  6. 如何用正则将多个空格看成一个空格结合spllit()方法将文本数据入库
  7. PHP系列笔记——Zend_Controller工作流程
  8. 安卓CTS官方文档之兼容性测试套件简介
  9. robin 今日南
  10. Request 地址栏传值
  11. fstream 学习
  12. 当yum安装出现Error: Package: glibc-headers .....时
  13. zabbix添加nginx监控
  14. VirtualBox安装CENTOS7.3常见问题
  15. MVC模块化开发方案
  16. PHP判断是否都是中文
  17. vue生成路由实例
  18. Teamwork(The seventh day of the team)
  19. 华为S5300系列交换机V100R005SPH020升级补丁
  20. HTML 页面中的 SVG

热门文章

  1. C#反射与特性(四):实例化类型
  2. ThreeJS 物理材质shader源码分析(像素着色器)
  3. 01--java--语言概述
  4. 工具之awk
  5. Oracle监听器
  6. 【WPF学习】第三十四章 资源基础
  7. Python用WMI模块获取windowns系统信息
  8. java设计模式2————工厂模式
  9. Request和Session的生命周期
  10. LaTeX技巧472:定义一个LaTeX参考文献不带编号且有缩进的方法