Consider this Spring Boot code that generates a JWT token. What will be the value of token after execution?
String token = Jwts.builder() .setSubject("user123") .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 60000)) .signWith(Keys.hmacShaKeyFor("mysecretkeymysecretkeymysecretkey12".getBytes()), SignatureAlgorithm.HS256) .compact();
Look at the signWith method and the key length used.
The code creates a JWT token with subject 'user123', sets issued and expiration times, and signs it with a valid HMAC SHA-256 key. The result is a valid JWT string.
Identify the correct fix for the syntax error in this JWT generation snippet:
Jwts.builder()
.setSubject("user")
.signWith(Keys.hmacShaKeyFor("secretkeysecretkeysecretkey12".getBytes())
.compact();Count the parentheses carefully.
The method call to hmacShaKeyFor is missing a closing parenthesis, causing a syntax error. Adding it fixes the code.
Examine this code snippet:
byte[] keyBytes = "shortkey".getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
String token = Jwts.builder()
.setSubject("admin")
.signWith(key, SignatureAlgorithm.HS256)
.compact();Why does it throw an InvalidKeyException?
Check the required key length for HMAC SHA-256.
HS256 requires a key of at least 256 bits (32 bytes). The provided key is shorter, causing the exception.
Given this code snippet:
long now = System.currentTimeMillis();
String token = Jwts.builder()
.setSubject("user")
.setIssuedAt(new Date(now))
.setExpiration(new Date(now + 300000))
.signWith(Keys.hmacShaKeyFor("mysecretkeymysecretkeymysecretkey12".getBytes()), SignatureAlgorithm.HS256)
.compact();How long is the token valid after issuance?
Look at the value added to now for expiration.
The expiration is set to 300000 milliseconds (5 minutes) after the issued time.
Why are JWT tokens considered stateless when used for authentication in Spring Boot?
Think about where the user data lives when using JWT.
JWT tokens carry all necessary user data and claims inside the token, so the server does not need to keep session state, making them stateless.