WCX19880905 2021-10-15 19:53 采纳率: 18.8%
浏览 22

spring boot 自定义jwt拦截器 提示找不到源

/**

  • jwt 后台访问拦截 拦截器配置文件 config

  • /
    @Configuration
    public class JwtInterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

      // 默认拦截所有路径
      registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**");
    

    }

    @Bean
    public JwtAuthenticationInterceptor authenticationInterceptor() {

      //这里报错  提示找不到源
      return new JwtAuthenticationInterceptor();
    

    }

}

/** 自定义拦截**/
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Object object) throws Exception {
    // 从请求头中取出 token 这里需要和前端约定好把jwt放到请求头一个叫token的地方
    String token = httpServletRequest.getHeader("token");
    // 如果不是映射到方法直接通过
    if (!(object instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) object;
    Method method = handlerMethod.getMethod();
    // 检查是否有passtoken注释,有则跳过认证
    if (method.isAnnotationPresent(PassToken.class)) {
        PassToken passToken = method.getAnnotation(PassToken.class);
        if (passToken.required()) {
            return true;
        }
    }
    // 默认全部检查
    else {
        System.out.println("被jwt拦截需要验证");
        // 执行认证
        if (token == null) {
            // 未登录非法操作

            throw new RuntimeException("无token,请重新登录");
        }

        // 获取 token 中的 user Name
        String userId = JwtUtils.getAudience(token);
        if (userId == null) {
            // 未登录非法操作

            throw new RuntimeException("无token,请重新登录");
        }

        // 获取载荷内容
        String userName = JwtUtils.getClaimByName(token, "userName").asString();
        String realName = JwtUtils.getClaimByName(token, "realName").asString();

        // 放入attribute以便后面调用
        httpServletRequest.setAttribute("userName", userName);
        httpServletRequest.setAttribute("realName", realName);

        return true;

    }
    return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
        ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Object o, Exception e) throws Exception {
}

}

  • 写回答

1条回答 默认 最新

  • 普通网友 2021-10-15 20:07
    关注

    你确定只有这些?

    评论

报告相同问题?

问题事件

  • 创建了问题 10月15日

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况