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

配置与示例请先阅读第一篇:https://blog.csdn.net/qq_37534947/article/details/132066909

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 超过有效期时间内进行解析

  • 有效期进行解析,验证抛出过期异常
    在这里插入图片描述
posted @   小小新一枚  阅读(400)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示