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();
    }
相关推荐
Adellle28 分钟前
Java中同步和异步的区别,以及阻塞和非阻塞的区别
java·开发语言
qq_124987075333 分钟前
基于springboot+vue的物流管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
学习编程的Kitty2 小时前
JavaEE初阶——多线程(5)单例模式和阻塞队列
java·开发语言·单例模式
m0_372257022 小时前
项目下有多个模块,每个模块有pom文件,是怎么继承的
java·tomcat
刘一说2 小时前
深入理解 Spring Boot Actuator:构建可观测性与运维友好的应用
运维·spring boot·后端
oak隔壁找我2 小时前
Spring AI 入门教程,使用Ollama本地模型集成,实现对话记忆功能。
java·人工智能·后端
懒羊羊不懒@2 小时前
JavaSe—Stream流☆
java·开发语言·数据结构
郝开2 小时前
最终 2.x 系列版本)2 - 框架搭建:pom配置;多环境配置文件配置;多环境数据源配置;测试 / 生产多环境数据源配置
java·spring boot·后端
用户3777967210962 小时前
RabbitMQ Unacked 消息深度解析:机制、问题与解决方案
spring boot·rabbitmq
Homeey2 小时前
深入理解ThreadLocal:从原理到架构实践的全面解析
java·后端