现在,我使用这段代码在我的项目中生成一个JWT令牌并设置一个过期时间:
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();但它告诉我:
Both 'payload' and 'claims' cannot both be specified. Choose either one.那么,我应该如何使用令牌设置过期时间呢?
发布于 2021-06-17 03:35:02
playload和claim应该选择其中之一,setExpiration属于索赔,所以只需像下面这样修改代码:
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;
}发布于 2021-06-17 02:24:21
根据这,有效载荷必须是纯文本(非JSON)字符串。您可以尝试对该值进行base64编码,或者可能通过Jwts.claims()创建一个声明。
你能详细说明你的目标是什么吗?
https://stackoverflow.com/questions/68012008
复制相似问题