Reputation: 38763
Now I am using this code to generate a JWT token and set an expire time in my project:
SecretKey secretKey = new SecretKeySpec(jwtSignKey.getBytes(), SignatureAlgorithm.HS256.getJcaName());
JwtPayload jwtPayload = new JwtPayload();
jwtPayload.setUserId(user.getId());
jwtPayload.setDeviceId(request.getDeviceId());
jwtPayload.setAppId(Long.valueOf(request.getApp().getKey()));
byte[] bytesEncoded = Base64.encodeBase64(JSON.toJSONString(jwtPayload).getBytes());
String accessToken = Jwts.builder().setPayload(new String(bytesEncoded))
.setExpiration(new Date(System.currentTimeMillis() + 30*1000))
.signWith(secretKey).compact();
but it tell me:
Both 'payload' and 'claims' cannot both be specified. Choose either one.
then what should I do to set a expire time with the token?
Upvotes: 0
Views: 2784
Reputation: 38763
playload and claim should choose one of then, setExpiration
belong claim, so just tweak code like this:
public static String generateAccessToken(String jwtSignKey, JwtPayload jwtPayload) {
SecretKey secretKey = new SecretKeySpec(jwtSignKey.getBytes(), SignatureAlgorithm.HS256.getJcaName());
ObjectMapper objectMapper = new ObjectMapper();
Map claims = objectMapper.convertValue(jwtPayload, Map.class);
String accessToken = Jwts.builder().setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + 30 * 1000))
.signWith(secretKey).compact();
return accessToken;
}
Upvotes: 0