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();
    }
相关推荐
hongtianzai2 分钟前
Laravel8.x核心特性全解析
java·c语言·开发语言·golang·php
逸Y 仙X5 分钟前
文章十一:ElasticSearch Dynamic Template详解
java·大数据·数据库·elasticsearch·搜索引擎·全文检索
隔壁小邓7 分钟前
IDEA 中同时启动多个微服务
java·微服务·intellij-idea
:1217 分钟前
idea17创建tomcat项目(计网底层核心理解!)
java·ide·intellij-idea
Brookty11 分钟前
网络通信核心:四元组、socket与IO机制详解
java·网络通信·网络入门
计算机徐师兄13 分钟前
Java基于SpringBoot的运动健康小程序【附源码、文档说明】
spring boot·小程序·运动健康·java运动健康小程序·运动健康小程序·java运动健康微信小程序·运动健康微信小程序
佩奇大王21 分钟前
P159 摆动序列
java·开发语言·算法
计算机学姐23 分钟前
基于SpringBoot的网吧管理系统
java·spring boot·后端·spring·tomcat·intellij-idea·mybatis
Boop_wu25 分钟前
[Java EE 进阶] SpringBoot 配置文件全解析:properties 与 yml 的使用(1)
java·spring boot·spring·java-ee
我不是秋秋26 分钟前
软件开发项目各角色关系解析:产品/前后端/测试如何高效协作?
java·算法·面试·职场和发展·哈希算法