在已签名的 jwt 令牌中设置为 Claim 的相同到期日期未返回

same expiry date not returned whee set as Claim in signed jwt token

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

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()”,将更容易注意到此问题