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();
    }
相关推荐
Wilson Chen5 分钟前
Spring Boot 多级缓存实现与优化:从本地缓存到 Redis
spring boot·redis·缓存
少废话h23 分钟前
Flume Kafka源与汇的topic覆盖问题解决
java·linux·kafka·flume
激动的兔子35 分钟前
Geoserver修行记-连接瀚高数据库显示java.sql.SQLException: org.postgresql.util.PSQLException
java·geoserver·瀚高数据库
一 乐1 小时前
健康打卡|健康管理|基于java+vue+的学生健康打卡系统设计与实现(源码+数据库+文档)
android·java·数据库·vue.js·spring boot·微信小程序
ghie90901 小时前
使用Java实现用户的注册和登录流程
java·数据库·oracle
颜如玉1 小时前
动态拼接SQL实践备忘📝
java·sql·mybatis
952361 小时前
数据结构-堆
java·数据结构·学习·算法
by__csdn1 小时前
Spring Boot 全面解析
java·数据库·spring boot·后端·spring
她说..1 小时前
基于Redis实现的分布式唯一编号生成工具类
java·数据库·redis·分布式·springboot
西岭千秋雪_1 小时前
Kafka客户端参数(一)
java·分布式·后端·kafka·linq