HashMap<String, Object> map = new HashMap<>();
// you can put any data in the map
map.put("userId", String.valueOf(userId));
map.put("xxx", xxx);
map.put("ddd", ddd);
long nowMillis = System.currentTimeMillis();
JwtBuilder jwtBuilder =
Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS512, SECRET);
// 過期時間
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
jwtBuilder.setExpiration(exp);
}
return jwtBuilder.compact();
鑒權
public static Map<String, Object> validateToken(String token) {
try {
// parse the token.
Map<String, Object> body = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token.replace("Bearer", "")).getBody();
return body;
} catch (ExpiredJwtException e) {
throw new AuthBizException(xxx, "簽名已經過期");
} catch (Exception e) {
throw new AuthBizException(xxx, "簽名驗證失敗");
}
}