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();
    }
相关推荐
霍田煜熙4 分钟前
【无标题】
java
q_19132846954 分钟前
基于Springboo和vue开发的企业批量排班系统人脸识别考勤打卡系统
前端·javascript·vue.js·spring boot·mysql·毕业设计·人脸识别
无忧智库6 分钟前
深度拆解:某大型医院“十五五”智慧医院建设方案,如何冲刺互联互通五级乙等?(附技术架构与实施路径)
java·数据库·架构
守护砂之国泰裤辣16 分钟前
Windows+docker下简单kafka测试联调
java·运维·spring boot·docker·容器
代码方舟18 分钟前
Java企业级风控实战:对接天远多头借贷行业风险版API构建信贷评分引擎
java·开发语言
Maiko Star29 分钟前
Word工具类——实现导出自定义Word文档(基于FreeMarker模板引擎生成动态内容的Word文档)
java·word·springboot·工具类
优雅的38度30 分钟前
maven的多仓库配置理解
java·架构
周末吃鱼36 分钟前
研发快速使用JMeter
java·jmeter
EntyIU37 分钟前
自己实现mybatisplus的批量插入
java·后端
小途软件1 小时前
基于深度学习的人脸检测算法研究
java·人工智能·pytorch·python·深度学习·语言模型