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();
    }
相关推荐
IT界的奇葩4 分钟前
代码规范 spring-javaformat使用
java·spring·代码规范
披着羊皮不是狼12 分钟前
多用户跨学科交流系统(4)参数校验+分页搜索全流程的实现
java·spring boot
小池先生1 小时前
Gradle vs Maven 详细对比
java·maven
q***23921 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
q***78781 小时前
Spring Boot的项目结构
java·spring boot·后端
百***17071 小时前
Spring Boot spring.factories文件详细说明
spring boot·后端·spring
q***96581 小时前
Spring Data JDBC 详解
java·数据库·spring
Kuo-Teng2 小时前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划
倚肆2 小时前
HttpServletResponse 与 ResponseEntity 详解
java·后端·spring
Q_Q5110082852 小时前
python+django/flask的宠物用品系统vue
spring boot·python·django·flask·node.js·php