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();
    }
相关推荐
我爱Jack4 分钟前
深入解析 LinkedList
java·开发语言
一线大码36 分钟前
Gradle 高级篇之构建多模块项目的方法
spring boot·gradle·intellij idea
27669582921 小时前
tiktok 弹幕 逆向分析
java·python·tiktok·tiktok弹幕·tiktok弹幕逆向分析·a-bogus·x-gnarly
用户40315986396632 小时前
多窗口事件分发系统
java·算法
用户40315986396632 小时前
ARP 缓存与报文转发模拟
java·算法
小林ixn2 小时前
大一新手小白跟黑马学习的第一个图形化项目:拼图小游戏(java)
java
nbsaas-boot2 小时前
Go语言生态成熟度分析:为何Go还无法像Java那样实现注解式框架?
java·开发语言·golang
hi0_62 小时前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
congvee2 小时前
springboot 学习第1期 - 创建工程
spring boot
朝如青丝暮成雪_2 小时前
java的三大特征
java