当前位置: 首页 > news >正文

SpringSecurity 捕获自定义JWT过滤器抛出的异常

自定义过滤器如下:

/*** jwt过滤器,验证令牌是否合法** @author 朱铭健*/
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {//换成你自己的获取Token方式String token = "";if (StringUtil.isNotNullOrEmpty(token)) {try {//TODO 这里写校验逻辑和抛出异常} catch (JWTException e) {//这里的JwtAuthException是一个自定义的AuthenticationExceptionthrow new JwtAuthException(e.getMessage());} catch (Exception e) {log.error("JWT认证异常 - {}:", token, e);//这里的JwtAuthException是一个自定义的AuthenticationExceptionthrow new JwtAuthException("JWT认证异常");}}filterChain.doFilter(request, response);}
}

定义一个 AuthenticationEntryPoint

/*** @author 朱铭健*/
@Slf4j
@Component
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint{@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {//使用response处理你的异常,包括响应json,跳转页面等}
}

配置 Configurer,关键是要将过滤器置于ExceptionTranslationFilter之后,异常处理是由ExceptionTranslationFilter实现的

public class JwtAuthenticationConfigurer extends AbstractHttpConfigurer<JwtAuthenticationConfigurer, HttpSecurity> {@Overridepublic void configure(HttpSecurity builder) {JwtAuthenticationFilter filter = new JwtAuthenticationFilter();// 务必注意这里与配置类中声明的先后顺序builder.addFilterAfter(filter, ExceptionTranslationFilter.class);}
}
    public SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {//Jwt相关配置http.with(new JwtAuthenticationConfigurer(), Customizer.withDefaults());return http.build();}
http://www.lryc.cn/news/463833.html

相关文章:

  • 中小型企业网络的设计与实现
  • 小马识途海外媒体推广有何优势?
  • Spring Boot知识管理:跨平台集成方案
  • 逆向工程基本流程
  • target_include_directories是如何组织头文件的?
  • 【Flutter】Dart:运算符
  • ChatGPT01-preivew体验报告:内置思维链和多个llm组合出的COT有啥区别呢?丹田与练气+中学生物理奥赛题测试,名不虚传还是名副其实?
  • 《云计算网络技术与应用》实训6-1:配置KVM虚拟机使用NAT网络
  • 【Unity新闻】Unity 6 正式版发布
  • 基于语音识别的停车共享小程序(lw+演示+源码+运行)
  • 编程考古-计算机发展(上)
  • pc轨迹回放制作
  • 无向图中的一些问题与处理(上接无向图知识简记)
  • AIGC助力小学生编程梦:C++入门不再难!
  • AI开发-三方库-Hugging Face-Pipelines
  • 【Python网络编程】学习Socket编程,打造网络应用!
  • docker (desktopcompose) download
  • 即时通讯:单聊消息逻辑
  • Libevent源码剖析之reactor
  • 分享一套SpringBoot+Vue民宿(预约)系统
  • Linux——应用软件的生命周期
  • 【Linux】exec系列函数详细介绍
  • ARINC 429总线协议
  • Qt解决槽函数中发送的信号的参数会变化带来的错误
  • C C++ 如何编写库级接口
  • 安装TDengine数据库3.3版本和TDengine数据库可视化管理工具
  • 详解CAS
  • 《环境感知方案:探索未来智能世界的关键技术》
  • Android 编译时出现Android resource linking failed.without required default value.
  • golang ws升级为wss