dljx-springboot

导航

 

1. 定义拦截器JwtValidatorInterceptor

点击查看代码
@Component
@Slf4j
public class JwtValidatorInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        log.debug(request.getRequestURI() + "需要验证: " + token);
        if(token != null){
            try {
                jwtUtil.parseToken(token);
                log.debug(request.getRequestURI() + "验证通过");
                return true;
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
        log.debug(request.getRequestURI() + "验证失败,禁止访问");
        response.setContentType("application/json;charset=utf-8");
        Result<Object> fail = Result.fail(20003, "jwt无效,请重新登录");
        response.getWriter().write(JSON.toJSONString(fail));
        return false;//拦截
    }
}

2. 注册拦截器

点击查看代码
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    @Autowired
    private JwtValidatorInterceptor jwtValidatorInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(jwtValidatorInterceptor);
        registration.addPathPatterns("/**")
                .excludePathPatterns(
                        "/user/login",
                        "/user/info",
                        "user/logout"
                );
    }
}

3. ces

登录接口放行,产生了一个jwt

错误接口

测试:手动修改token

提示失败

posted on 2023-07-13 16:10  丹狼键仙  阅读(37)  评论(0编辑  收藏  举报