其他分享
首页 > 其他分享> > jjwt生成以及验证token

jjwt生成以及验证token

作者:互联网

这里写目录标题

引入依赖:

 <!--jwt依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

创建token

 /**
     * @description: 创建token
     * @param: []
     * @return: void
     * @author 孙
     * @date: 2022/1/6 9:37
     */
   @Test
    public void testCreateToken(){
       //创建jwtBuilder对象
        JwtBuilder builder = Jwts.builder()
                //声明的表示
                .setId("8888")
                //主体,用户("sub","Rose")
                .setSubject("Rose")
                //创建日期
                .setIssuedAt(new Date())
                //加密方式
                .signWith(SignatureAlgorithm.HS256,"xxxx");

        //获取jwt的token
       String token=builder.compact();
       System.out.println(token);

       System.out.println("=============================================");
       String[] split=token.split("\\.");
       System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
       System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
       //无法解密
       System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
   }

解析token

/**
    * @description: 解析token
    * @param: []
    * @return: void
    * @author 孙
    * @date: 2022/1/6 9:48
    */
   @Test
    public void testParseToken(){
       String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY0MTQzMzQ3OX0.CgQlfnY-8wlZQINZpqcX9SerdkfPUv7tjtPllyGbi2c";
       //解析token获取负载中声明的对象
        Claims claims = Jwts.parser()
                //设置自定义私钥
               .setSigningKey("xxxx")
                //添加token进行解析
               .parseClaimsJws(token)
                //获取解析的主体
               .getBody();
       System.out.println("id"+claims.getId());
       System.out.println("subject"+claims.getSubject());
       System.out.println("issuedAt"+claims.getIssuedAt());
   }

设置token失效时间

 /**
    * @description: 设置token失效时间
    * @param: []
    * @return: void
    * @author 孙
    * @date: 2022/1/6 9:57
    */
   @Test
    public void testCreateTokenHasExp(){
       //当前系统时间
       long currentTimeMillis = System.currentTimeMillis();
       //过期时间,1分钟
        long exp = currentTimeMillis + 60 * 1000;


       //创建jwtBuilder对象
       JwtBuilder builder = Jwts.builder()
               //声明的表示
               .setId("8888")
               //主体,用户("sub","Rose")
               .setSubject("Rose")
               //创建日期
               .setIssuedAt(new Date())
               //设置过期时间
               .setExpiration(new Date(exp))
               //加密方式
               .signWith(SignatureAlgorithm.HS256,"xxxx");

       //获取jwt的token
       String token=builder.compact();
       System.out.println(token);

       System.out.println("=============================================");
       String[] split=token.split("\\.");
       System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
       System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
       //无法解密
       System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
   }

解析token(失效时间)

/**
     * @description: 解析token(失效时间)
     * 失效会报异常io.jsonwebtoken.ExpiredJwtException: JWT expired at 2022-01-06T10:02:16Z. Current time: 2022-01-06T10:
     * @param: []
     * @return: void
     * @author 孙
     * @date: 2022/1/6 9:48
     */
    @Test
    public void testParseTokenHasExp(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY0MTQzNDQ3NiwiZXhwIjoxNjQxNDM0NTM2fQ.P5TCCMpNo4pN4oef286h7LjICTJbB-qt-L8dRfM1hN0";
        //解析token获取负载中声明的对象
        Claims claims = Jwts.parser()
                //设置自定义私钥
                .setSigningKey("xxxx")
                //添加token进行解析
                .parseClaimsJws(token)
                //获取解析的主体
                .getBody();
        System.out.println("id:"+claims.getId());
        System.out.println("subject:"+claims.getSubject());
        System.out.println("issuedAt:"+claims.getIssuedAt());
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("签发时间:"+simpleDateFormat.format(claims.getIssuedAt()));
        System.out.println("过期时间:"+simpleDateFormat.format(claims.getExpiration()));
        System.out.println("当前时间:"+simpleDateFormat.format(new Date()));

    }

创建token(自定义声明)

/**
     * @description: 创建token(自定义声明)
     * @param: []
     * @return: void
     * @author 孙
     * @date: 2022/1/6 9:57
     */
    @Test
    public void testCreateTokenByClaims(){
        //当前系统时间
        long currentTimeMillis = System.currentTimeMillis();
        //过期时间,1分钟
        long exp = currentTimeMillis + 60 * 1000;

         HashMap<String, Object> map = new HashMap<>();
         map.put("role","a");
         map.put("name","aa");


        //创建jwtBuilder对象
        JwtBuilder builder = Jwts.builder()
                //声明的表示
                .setId("8888")
                //主体,用户("sub","Rose")
                .setSubject("Rose")
                //创建日期
                .setIssuedAt(new Date())
                //设置过期时间
                .setExpiration(new Date(exp))
                //加密方式
                .signWith(SignatureAlgorithm.HS256,"xxxx")
                .claim("roles","admin")
                .claim("logo","xxx.jpg")
                //直接传入map
              /*  .addClaims(map)*/;


        //获取jwt的token
        String token=builder.compact();
        System.out.println(token);

        System.out.println("=============================================");
        String[] split=token.split("\\.");
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        //无法解密
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
    }

解析token(自定义声明)

/**
     * @description: 解析token(自定义声明)
     * 失效会报异常io.jsonwebtoken.ExpiredJwtException: JWT expired at 2022-01-06T10:02:16Z. Current time: 2022-01-06T10:
     * @param: []
     * @return: void
     * @author 孙
     * @date: 2022/1/6 9:48
     */
    @Test
    public void testParseTokenByClaims(){
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4Iiwic3ViIjoiUm9zZSIsImlhdCI6MTY0MTQzNTM4OCwiZXhwIjoxNjQxNDM1NDQ4LCJyb2xlcyI6ImFkbWluIiwibG9nbyI6Inh4eC5qcGcifQ.8yen0bkd4Ep4fXm-WcsMxAIr01V-YDyYb06ZhRoiP9Y";
        //解析token获取负载中声明的对象
        Claims claims = Jwts.parser()
                //设置自定义私钥
                .setSigningKey("xxxx")
                //添加token进行解析
                .parseClaimsJws(token)
                //获取解析的主体
                .getBody();
        System.out.println("id:"+claims.getId());
        System.out.println("subject:"+claims.getSubject());
        System.out.println("issuedAt:"+claims.getIssuedAt());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("签发时间:"+simpleDateFormat.format(claims.getIssuedAt()));
        System.out.println("过期时间:"+simpleDateFormat.format(claims.getExpiration()));
        System.out.println("当前时间:"+simpleDateFormat.format(new Date()));
        System.out.println("roles:"+claims.get("roles"));
        System.out.println("logo:"+claims.get("logo"));

    }

标签:验证,System,jjwt,token,split,println,claims,out
来源: https://blog.csdn.net/sjgllllll/article/details/122337979