Complete the code to generate a JWT token using the secret key.
String token = Jwts.builder().setSubject(username).signWith([1]).compact();The signWith method requires a Key object. Using Keys.hmacShaKeyFor(secret.getBytes()) correctly creates the key for signing the JWT.
Complete the code to extract the username from the JWT token.
String username = Jwts.parserBuilder().setSigningKey([1]).build().parseClaimsJws(token).getBody().getSubject();The parser needs the signing key as a Key object to verify the token signature. Using Keys.hmacShaKeyFor(secret.getBytes()) provides the correct key.
Fix the error in the code that validates the JWT token expiration.
boolean isValid = !Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().getExpiration().[1](new Date());The token is valid if its expiration date is after the current date. Using before checks if expiration is before now, so negating it means valid if expiration is in the future.
Fill both blanks to create a JWT token with expiration time set to 1 hour from now.
String token = Jwts.builder().setSubject(user).setExpiration(new Date(System.currentTimeMillis() [1] [2])).signWith(key).compact();
To set expiration 1 hour from now, add 1 hour in milliseconds to current time. 1 hour = 60 * 60 * 1000 ms, so use System.currentTimeMillis() + 60 * 60 * 1000.
Fill all three blanks to parse the JWT token, extract claims, and get the 'roles' claim as a list.
Claims claims = Jwts.parserBuilder().setSigningKey([1]).build().parseClaimsJws(token).getBody(); List<String> roles = claims.get([2], [3]);
The signing key is needed to parse the token. The 'roles' claim is extracted by its name as a List, so use claims.get("roles", List.class).