资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringBoot集成JWT怎么生成token和校验-创新互联

这篇文章主要讲解了“SpringBoot集成JWT怎么生成token和校验”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot集成JWT怎么生成token和校验”吧!

创新互联建站是一家集网站建设,石鼓企业网站建设,石鼓品牌网站建设,网站定制,石鼓网站建设报价,网络营销,网络优化,石鼓网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

封装JTW生成token和校验方法

public class JwtTokenUtil {

  //公用密钥-保存在服务端,客户端是不会知道密钥的,以防被攻击
  public static String SECRET = "ThisIsASecret";

  //生成Troke
  public static String createToken(String username) {
    //签发时间
    //Date iatDate = new Date();
    //过地时间 1分钟后过期
    //Calendar nowTime = Calendar.getInstance();
    //nowTime.add(Calendar.MINUTE, 1);
    //Date expiresDate = nowTime.getTime();
    Map map = new HashMap();
    map.put("alg", "HS256");
    map.put("typ", "JWT");
    String token = JWT.create()
          .withHeader(map)
          //.withClaim( "name","Free码生") //设置 载荷 Payload
          //.withClaim("age","12")
          //.withClaim( "org","测试")
          //.withExpiresAt(expiresDate)//设置过期时间,过期时间要大于签发时间
          //.withIssuedAt(iatDate)//设置签发时间
          .withAudience(username) //设置 载荷 签名的观众
          .sign(Algorithm.HMAC256(SECRET));//加密
    System.out.println("后台生成token:" + token);
    return token;
  }

  //校验TOKEN
  public static boolean verifyToken(String token) throws UnsupportedEncodingException{
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
    try {
      verifier.verify(token);
      return true;
    } catch (Exception e){
      return false;
    }
  }

  //获取Token信息
  public static DecodedJWT getTokenInfo(String token) throws UnsupportedEncodingException{
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
    try{
      return verifier.verify(token);
    } catch(Exception e){
      throw new RuntimeException(e);
    }
  }

}

新建自定义注解:@UserLoginToken

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
  boolean required() default true;
}

关于拦截器配置:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authenticationInterceptor())
        .addPathPatterns("/**");  // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
  }
  @Bean
  public AuthenticationInterceptor authenticationInterceptor() {
    return new AuthenticationInterceptor();
  }
}
public class AuthenticationInterceptor implements HandlerInterceptor {
  @Autowired
  UserService userService;
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
    String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 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;
      }
    }
    //检查有没有需要用户权限的注解
    if (method.isAnnotationPresent(UserLoginToken.class)) {
      UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
      if (userLoginToken.required()) {
        // 执行认证
        if (token == null) {
          throw new RuntimeException("无token,请重新登录");
        }
        // 验证 token
        if(JwtTokenUtil.verifyToken(token)){
          return true;
        }else {
          throw new RuntimeException("401");
        }
      }
    }
    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 {
  }
}

登录:

在Controller上登录方法不用添加@UserLoginToken自定义注解,其余获取后台数据方法加上@UserLoginToken自定义注解,目的验证token是否有效,是则返回数据,否则提示401无权限。

测试:

@Controller
@RequestMapping(path = "/api")
public class IndexController {

  private String prefix = "index/";

  @GetMapping("/index")
  public String index()
  {
    return prefix + "index";
  }

  @UserLoginToken
  @PostMapping("/test")
  @ResponseBody
  public Object test(){
    Map map = new HashMap<>();
    map.put("code","200");
    map.put("message","你已通过验证了");
    return map;
  }
}

HTTP请求带上登陆成功后生成token,返回成功:

SpringBoot集成JWT怎么生成token和校验

HTTP请求带上无效token或不带token,返回失败:

SpringBoot集成JWT怎么生成token和校验

感谢各位的阅读,以上就是“SpringBoot集成JWT怎么生成token和校验”的内容了,经过本文的学习后,相信大家对SpringBoot集成JWT怎么生成token和校验这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联建站,小编将为大家推送更多相关知识点的文章,欢迎关注!

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻标题:SpringBoot集成JWT怎么生成token和校验-创新互联
文章转载:http://cdkjz.cn/article/dcjcgg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220