在SpringBoot項目上構建JWT訪問token和刷新token時,遇到一個Date類型的問題,由於序列化JWT token時只支持秒,將毫秒級自然丟棄。
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
如果有基於簽發時間戳(iat,IssuedAt)的應用,需要特別小心,這是一個坑,比如作爲驗證。
解析分發的token,包括exp,nbf,iat:
{
...
"exp": 1594351823,
"iat": 1593747023,
...
}
發現都是秒級而非毫秒級的,一般代碼中,我們會使用毫秒timestamp:
//簽發時間
final Date issusedAtTime = new Date();
jwtBuilder.withIssuedAt(issusedAtTime);
long timestamp = issusedAtTime.getTime();
經過讀JWT源碼分析,序列化主要是PayloadSerializer,通過方法dateToSeconds明確了JWT中的日期全部按秒序列化:
public class PayloadSerializer extends StdSerializer<ClaimsHolder> {
....
private long dateToSeconds(Date date) {
return date.getTime() / 1000L;
}
}
順便研究了下解析類PayloadDeserializer,通過方法getDateFromSeconds將秒級的日期,轉換爲毫秒然後構造Date對象:
class PayloadDeserializer extends StdDeserializer<Payload> {
....
public Payload deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Map<String, JsonNode> tree = (Map)p.getCodec().readValue(p, new TypeReference<Map<String, JsonNode>>() {
});
if (tree == null) {
throw new JWTDecodeException("Parsing the Payload's JSON resulted on a Null map");
} else {
String issuer = this.getString(tree, "iss");
String subject = this.getString(tree, "sub");
List<String> audience = this.getStringOrArray(tree, "aud");
Date expiresAt = this.getDateFromSeconds(tree, "exp");
Date notBefore = this.getDateFromSeconds(tree, "nbf");
Date issuedAt = this.getDateFromSeconds(tree, "iat");
String jwtId = this.getString(tree, "jti");
return new PayloadImpl(issuer, subject, audience, expiresAt, notBefore, issuedAt, jwtId, tree, this.objectReader);
}
}
....
Date getDateFromSeconds(Map<String, JsonNode> tree, String claimName) {
JsonNode node = (JsonNode)tree.get(claimName);
if (node != null && !node.isNull()) {
if (!node.canConvertToLong()) {
throw new JWTDecodeException(String.format("The claim '%s' contained a non-numeric date value.", claimName));
} else {
long ms = node.asLong() * 1000L;
return new Date(ms);
}
} else {
return null;
}
}
....
}
至此,破案成功!