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

自定义过滤器如下:

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

定义一个 AuthenticationEntryPoint

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

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

java 复制代码
public class JwtAuthenticationConfigurer extends AbstractHttpConfigurer<JwtAuthenticationConfigurer, HttpSecurity> {

    @Override
    public void configure(HttpSecurity builder) {
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        // 务必注意这里与配置类中声明的先后顺序
        builder.addFilterAfter(filter, ExceptionTranslationFilter.class);
    }
}
java 复制代码
    public SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
        //Jwt相关配置
        http.with(new JwtAuthenticationConfigurer(), Customizer.withDefaults());
        return http.build();
    }
相关推荐
0xDevNull4 分钟前
分布式事务实战指南:从理论到Seata落地
java·开发语言·后端
椰猫子9 分钟前
Spring Framework(Bean)
java·前端·spring
道清茗10 分钟前
【RH294知识点汇总】第 7 章 《 使用角色和 Ansible 内容集合简化 Playbook 》
java·前端·ansible
南境十里·墨染春水19 分钟前
linux学习进展 线程同步——条件变量
java·开发语言·学习
窥视未来26 分钟前
MySQL 性能调优完全指南:从硬件到 SQL,一篇吃透
java·数据库
普修罗双战士31 分钟前
【开发工具IDEA调试,高频使用, IntelliJ IDEA 调试快捷键完全指南】
java·开发语言·intellij-idea
阿丰资源41 分钟前
基于SpringBoot+MySQL的校园管理系统设计与实现(源码+文档+数据库,直接运行)
数据库·spring boot·mysql
XS0301061 小时前
Java 基础(十)异常
java·开发语言·oracle
_F_y1 小时前
C++11 异步操作实现线程池
java·jvm·c++
Lumos_7771 小时前
Linux -- 共享内存
java·linux·运维