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();
    }
相关推荐
怪兽201418 分钟前
SQL优化手段有哪些
java·数据库·面试
ss27322 分钟前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
Deschen1 小时前
设计模式-原型模式
java·设计模式·原型模式
麦麦鸡腿堡1 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
それども1 小时前
SpringBootTest运行线程池被拒绝
java
介一安全2 小时前
【Frida Android】基础篇6:Java层Hook基础——创建类实例、方法重载、搜索运行时实例
android·java·网络安全·逆向·安全性测试·frida
xyy20252 小时前
Spring事务的传播方式
java·数据库·spring
@Kerry~2 小时前
phpstudy .htaccess 文件内容
java·开发语言·前端
roshy2 小时前
x86、arm、rsc-v指令集架构,指令集、OS、应用3者的关系
java·arm开发·架构
CRMEB系统商城2 小时前
CRMEB多商户系统(PHP)v3.3正式发布,同城配送上线[特殊字符]
java·开发语言·小程序·php