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();
    }
相关推荐
如果丶可以坑几秒前
maven无法获取依赖问题
java·maven·1024程序员节
兜兜风d'22 分钟前
RabbitMQ 持久性详解
spring boot·分布式·rabbitmq·1024程序员节
blammmp22 分钟前
RabbitMQ :概述,Web界面介绍,快速上手,工作模式
java·分布式·rabbitmq
何中应23 分钟前
如何截取PDF内容为图片
java·开发语言·后端·pdf
哈皮Superman1 小时前
【Research】MagicFuzzer: Scalable deadlock detection for large-scale applications
java·开发语言·数据库
问道飞鱼1 小时前
【微服务组件】Springboot结合Dubbo实现RPC调用
spring boot·微服务·rpc·dubbo
I'm Jie2 小时前
(二)Gradle 依赖仓库及安全凭证配置
java·spring boot·spring·gradle·maven
牢七2 小时前
CATWIFI
java
信码由缰2 小时前
单体架构中的事件驱动架构:Java应用程序的渐进式重构
java
初学小白...3 小时前
实现Runnable接口
java·开发语言