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();
    }
相关推荐
小旭952716 小时前
Spring MVC :从入门到精通(上)
java·后端·spring·mvc·intellij-idea
阿杜杜不是阿木木16 小时前
从0到1构建像Claude Code那样的Agent(三):行动前先计划
java·服务器·windows·agent·ai编程·claudecode
StackNoOverflow16 小时前
Spring MVC核心知识点快速梳理
java·spring·mvc
步步为营DotNet16 小时前
使用.NET 11的Native AOT提升应用性能
java·前端·.net
jing-ya16 小时前
day 54 图论part6
java·开发语言·数据结构·算法·图论
深念Y16 小时前
Java并发集合:原理与使用场景速查
java·开发语言
恼书:-(空寄16 小时前
Spring Boot 实现事件监听(监听器+自定义事件)完整指南
java·spring boot·后端
我真会写代码16 小时前
深入解析Java ArrayList与HashMap扩容机制:原理、差异与实战避坑
java·数据结构·算法·集合
代码探秘者16 小时前
【大模型应用】3.分块入门
java·后端·python·spring
独断万古他化17 小时前
【抽奖系统开发实战】Spring Boot 抽奖模块全解析:MQ 异步处理、缓存信息、状态扭转与异常回滚
java·spring boot·redis·后端·缓存·rabbitmq·mvc