程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期?

开发过程中遇到在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期的问题如何解决?下面主要结合日常开发的经验,给出你关于在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期的解决方法建议,希望对你解决在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期有所启发或帮助;

下面是一个示例程序,它没有从索赔中返回正确的到期日期。

package question;

import io.Jsonwebtoken.JwtParser;
import io.Jsonwebtoken.Jwts;
import io.Jsonwebtoken.io.Decoders;
import io.Jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

public class Sampletoken {

    public static voID main(String[] args) {
        String secretKey = new String("fhsdkjfhksjdfhdJskfhjksdfhjkdshfjksdhfjksdfhjkdshfsdjkhfdksjhfjkdshfdksjhkjfhdskjf");
        byte[] keyBytes = Decoders.BASE64.decode(secretKey);
        Key key = Keys.hmacShaKeyFor(keyBytes);

        Date expirationDate = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10);

        String jwt = Jwts.builder().setExpiration(expirationDate).signWith(key).compact();

        JwtParser signedParser = Jwts.parserBuilder().setSigningKey(secretKey).build();

        Date deserializedExpirationDate = signedParser.parseClaimsJws(jwt).getbody().getExpiration();

        System.out.println(expirationDate);
        System.out.println(deserializedExpirationDate);

        System.out.println("date and deserialized dates should be equal : " + expirationDate.compareto(deserializedExpirationDate));
    }
}

实际输出:-

Sun Mar 14 05:14:25 IST 2021
Sun Mar 14 05:14:25 IST 2021
date and deserialized dates should be equal : 1

预期输出:-

Sun Mar 14 05:14:25 IST 2021
Sun Mar 14 05:14:25 IST 2021
date and deserialized dates should be equal : 0

解决方法

JWT 日期精度为秒,而 Java 日期为毫秒。当日期被序列化时,额外的精度会丢失。您需要调整您的测试。

如果您使用 ISO 8601 格式或旧标准“getTime()”,则更容易注意到这个问题

大佬总结

以上是大佬教程为你收集整理的在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期全部内容,希望文章能够帮你解决在签名的 jwt 令牌中设置为 Claim 时未返回相同的到期日期所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: