Dolphin
Dolphin

Reputation: 38763

how to set expire of jwt when using jjwt

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

Answers (2)

Dolphin
Dolphin

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

Dave G
Dave G

Reputation: 9777

According to this, Payload must be a plaintext (NON-JSON) String. You could try base64 encoding that value or possibly creating a Claims via Jwts.claims()

Can you detail what you are aiming to do?

Upvotes: 1

Related Questions