JWT 使用入门(二)token有效期

64 阅读1分钟

@TOC

配置与示例请先阅读第一篇:blog.csdn.net/qq_37534947…

1.问题背景

  • 在具体的业务需求中,我们并不希望签发的token是永久生效的,所以我们可以为token添加一个过期时间。
  • 在Jwt的有效载荷中提供了默认7个字段,其中就包含过期时间,只需要在生成token的时候进行设置即可

2. token过期校验

2.1 生成token并设置有效时间1分钟

  • 生成token,设置有效时间1分钟,其中密钥设置为"itcast"

  • 注意签发时间需要小于过期时间

        public static String setJwt(){
            //这里为了方便测试,我们将过期时间设置为1分钟
            long now = System.currentTimeMillis();//当前时间
            long exp = now + 1000*60;//过期时间为1分钟
            JwtBuilder builder= Jwts.builder().setId("1111")
                    .setSubject("test")
                    .setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256,"itcast")
                    .setExpiration(new Date(exp));
            String token =  builder.compact();
            return token;
        }
    

2.2 验证token

  • 把上面生成的token传进该函数里进行验证,其中密钥和上面一样,同为“itcast”
    public static void getJwt(String token) {
        String compactJws= token;
        Claims claims = Jwts.parser().setSigningKey("itcast").parseClaimsJws(compactJws).getBody();
        System.out.println("id:"+claims.getId());
        System.out.println("subject:"+claims.getSubject());
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        System.out.println("签发时间:"+sdf.format(claims.getIssuedAt()));
        System.out.println("过期时间:"+sdf.format(claims.getExpiration()));
        System.out.println("当前时间:"+sdf.format(new Date()) );
    }

2.2.1 在有效期时间内进行解析

  • 有效期进行解析,验证通过 在这里插入图片描述

2.2.2 超过有效期时间内进行解析

  • 有效期进行解析,验证抛出过期异常 在这里插入图片描述