JWT如何解析过期的token中的信息

一、问题背景

  最近搭建springcloud的项目,项目采取了Jwt + spring security 来进行登录验证,Jwt token 锁定用户的失效时间,但是由于 jwt token特性导致token失效时间无法刷新,所以必须新创建一个token令牌,用来代替之前已失效token。

  (token失效时间无法刷新的原因是由于jwt创建token是根据jwt保存的相关信息来计算的,过期时间是其中的一个计算维度,所以一旦过期时间改了,那么生成的token值也就变了。)

  之后为了解决这个问题,结合了redis,将token值保存到redis中,用户操作后刷新redis的有效时间,这样如果jwt token失效了,再检查 redis 中保存token的key是否失效,如果没有失效,那么就重新创建jwt token ,失效了,就重新登录。

  我用一个过期token去调用接口,返回请求未授权。我查看token拦截的方法,发现是token解析异常,返回null导致接口返回未授权。token解析的最终处理都是parseJWT(jsonWebToken)这个方法,代码如下:

    public static Claims parseJWT(String jsonWebToken) {
        try {
            return Jwts.parser().setSigningKey(Base64.getDecoder().decode(getBase64Security())).parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception var2) {
            return null;
        }
    }

二、问题原因

根据报错堆栈信息找到了DefaultJwtParser类中,找到了问题的原因。

传入过期token,debug调试发现是在DefaultJwtParser的parse(String jwt)方法中返回了ExpiredJwtException 过期异常。部分代码如下

                boolean allowSkew = this.allowedClockSkewMillis > 0L;
                if (claims != null) {
                    Date now = this.clock.now();
                    long nowTime = now.getTime();
                    Date exp = claims.getExpiration();
                    String nbfVal;
                    SimpleDateFormat sdf;
                    if (exp != null) {
                        long maxTime = nowTime - this.allowedClockSkewMillis;
                        Date max = allowSkew ? new Date(maxTime) : now;
                        if (max.after(exp)) {
                            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                            String expVal = sdf.format(exp);
                            nbfVal = sdf.format(now);
                            long differenceMillis = maxTime - exp.getTime();
                            String msg = "JWT expired at " + expVal + ". Current time: " + nbfVal + ", a difference of " + differenceMillis + " milliseconds.  Allowed clock skew: " + this.allowedClockSkewMillis + " milliseconds.";
                            throw new ExpiredJwtException((Header)header, claims, msg);
                        }
                    }

                    Date nbf = claims.getNotBefore();
                    if (nbf != null) {
                        long minTime = nowTime + this.allowedClockSkewMillis;
                        Date min = allowSkew ? new Date(minTime) : now;
                        if (min.before(nbf)) {
                            sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                            nbfVal = sdf.format(nbf);
                            String nowVal = sdf.format(now);
                            long differenceMillis = nbf.getTime() - minTime;
                            String msg = "JWT must not be accepted before " + nbfVal + ". Current time: " + nowVal + ", a difference of " + differenceMillis + " milliseconds.  Allowed clock skew: " + this.allowedClockSkewMillis + " milliseconds.";
                            throw new PrematureJwtException((Header)header, claims, msg);
                        }
                    }

                    this.validateExpectedClaims((Header)header, claims);
                }

看到结尾的throw new ExpiredJwtException,我相信就找到了问题的关键,原来在在解析token并发现这个token已经过期了,它作出的反应是直接抛异常。

异常定义的构造方法中除了msg信息,还有claims和header信息。

检查claims发现,在异常之前token其实已经解析完毕。

这样也就代表着,抛出的这个异常 ExpiredJwtException 中有一个参数 claims 就是解析后的token,那么本次这个问题也就解决了。

  catch ExpiredJwtException 异常后,直接从异常中获取解析的数据即可。

三、方法处理

修改原来的parseJWT(jsonWebToken),代码如下:

    public static Claims parseJWT(String jsonWebToken) {
        try {
            return Jwts.parser().setSigningKey(Base64.getDecoder().decode(getBase64Security())).parseClaimsJws(jsonWebToken).getBody();
        } catch (ExpiredJwtException var) {
            return  var.getClaims();
        } catch (PrematureJwtException var1) {
            return var1.getClaims();
        } catch (Exception var2) {
            return null;
        }
    }

 

ExpiredJwtException 异常是超过token过期时间异常
PrematureJwtException 异常是早于token生效时间异议

附带判断token是否过期的方法代码:

    public Boolean isTokenExpired(String token) {
        //不管是否过期,都返回claims对象
        Claims claims = parseJWT(token);
        Date expiration = claims.getExpiration();
        //和当前时间进行对比来判断是否过期
        return new Date(System.currentTimeMillis()).after(expiration);
    }

最终测试,可以从过期的token中获取用户信息了,接口也不拦截过期token了(因为之间的拦截器代码是根据token能不能解析用户信息去拦截的)。

相关文章:

SpirngBoot设置自定义注解@NoToken去除部分接口的token验证_洛阳泰山的博客-CSDN博客

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泰山AI

原创不易,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值