Bird
Raised Fist0
Spring Bootframework~20 mins

JWT generation in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
JWT Mastery in Spring Boot
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this JWT generation snippet?

Consider this Spring Boot code that generates a JWT token. What will be the value of token after execution?

Spring Boot
String token = Jwts.builder()
  .setSubject("user123")
  .setIssuedAt(new Date())
  .setExpiration(new Date(System.currentTimeMillis() + 60000))
  .signWith(Keys.hmacShaKeyFor("mysecretkeymysecretkeymysecretkey12".getBytes()), SignatureAlgorithm.HS256)
  .compact();
AA valid JWT string with header, payload containing subject 'user123', and signature
BA plain string 'user123' without any JWT structure
CThrows a runtime exception due to invalid key length
DAn empty string because expiration is set in the past
Attempts:
2 left
💡 Hint

Look at the signWith method and the key length used.

📝 Syntax
intermediate
2:00remaining
Which option correctly fixes the syntax error in this JWT builder code?

Identify the correct fix for the syntax error in this JWT generation snippet:

Jwts.builder()
  .setSubject("user")
  .signWith(Keys.hmacShaKeyFor("secretkeysecretkeysecretkey12".getBytes())
  .compact();
ARemove the .compact() call at the end
BAdd a closing parenthesis after getBytes(): .signWith(Keys.hmacShaKeyFor("secretkeysecretkeysecretkey12".getBytes()))
CChange .setSubject("user") to .setSubject(user)
DReplace Keys.hmacShaKeyFor with new SecretKeySpec
Attempts:
2 left
💡 Hint

Count the parentheses carefully.

🔧 Debug
advanced
2:00remaining
Why does this JWT generation code throw an InvalidKeyException?

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?

AThe key length is too short for HS256 algorithm
BThe subject 'admin' is not allowed in JWT
CThe SignatureAlgorithm HS256 is deprecated
DThe getBytes() method returns null
Attempts:
2 left
💡 Hint

Check the required key length for HMAC SHA-256.

state_output
advanced
2:00remaining
What is the expiration time of the generated JWT token?

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?

A30 seconds
B1 hour
C5 minutes
DNo expiration set
Attempts:
2 left
💡 Hint

Look at the value added to now for expiration.

🧠 Conceptual
expert
3:00remaining
Which option best explains why JWT tokens are stateless in Spring Boot applications?

Why are JWT tokens considered stateless when used for authentication in Spring Boot?

ABecause JWT tokens require server memory to track each token's state
BBecause Spring Boot stores JWT tokens in a centralized database
CBecause JWT tokens expire immediately after creation
DBecause all user information and claims are stored inside the token itself, no server-side session is needed
Attempts:
2 left
💡 Hint

Think about where the user data lives when using JWT.

Practice

(1/5)
1. What is the main purpose of generating a JWT (JSON Web Token) in a Spring Boot application?
easy
A. To securely identify users without storing session data on the server
B. To store user passwords in the database
C. To create HTML pages dynamically
D. To manage database connections

Solution

  1. Step 1: Understand JWT purpose

    JWTs are used to securely identify users by encoding user info and signing it.
  2. Step 2: Compare options

    Only To securely identify users without storing session data on the server describes JWT's role in stateless authentication without server sessions.
  3. Final Answer:

    To securely identify users without storing session data on the server -> Option A
  4. Quick Check:

    JWT purpose = secure user identity without sessions [OK]
Hint: JWTs identify users without server sessions [OK]
Common Mistakes:
  • Confusing JWT with session storage
  • Thinking JWT stores passwords
  • Assuming JWT creates web pages
2. Which of the following code snippets correctly initializes a JWT builder using the jjwt library in Spring Boot?
easy
A. JwtBuilder().setSubject("user").sign(secretKey).build();
B. Jwts.builder().subject("user").sign(secretKey).compact();
C. Jwts.create().subject("user").signWith(secretKey).generate();
D. Jwts.builder().setSubject("user").signWith(secretKey).compact();

Solution

  1. Step 1: Recall jjwt syntax

    The correct method chain starts with Jwts.builder(), uses setSubject(), signWith(), then compact().
  2. Step 2: Check each option

    Jwts.builder().setSubject("user").signWith(secretKey).compact(); matches the correct method names and order. Others use incorrect method names or chaining.
  3. Final Answer:

    Jwts.builder().setSubject("user").signWith(secretKey).compact(); -> Option D
  4. Quick Check:

    Correct jjwt builder syntax = Jwts.builder().setSubject("user").signWith(secretKey).compact(); [OK]
Hint: Use Jwts.builder(), setSubject(), signWith(), compact() [OK]
Common Mistakes:
  • Using incorrect method names like sign() instead of signWith()
  • Missing Jwts.builder() start
  • Using create() or build() instead of compact()
3. Given the following code snippet, what will be the output type of the token variable?
String token = Jwts.builder()
  .setSubject("user123")
  .signWith(secretKey)
  .compact();
medium
A. A JSON object representing the token
B. A signed JWT string token
C. A byte array of the token
D. An exception is thrown

Solution

  1. Step 1: Understand compact() output

    The compact() method returns the JWT as a compact URL-safe string.
  2. Step 2: Analyze code snippet

    The code builds a JWT with subject and signs it, then calls compact(), so token is a String.
  3. Final Answer:

    A signed JWT string token -> Option B
  4. Quick Check:

    compact() returns String token [OK]
Hint: compact() returns JWT as a string [OK]
Common Mistakes:
  • Expecting a JSON object instead of string
  • Thinking output is byte array
  • Assuming code throws exception without error
4. Identify the error in this JWT generation code snippet:
String token = Jwts.builder()
  .setSubject("user")
  .signWith("mySecretKey")
  .compact();
medium
A. Jwts.builder() is not a valid method
B. setSubject() cannot accept a String
C. signWith() requires a Key object, not a String
D. compact() should be called before signWith()

Solution

  1. Step 1: Check signWith() parameter type

    signWith() expects a java.security.Key or SecretKey, not a plain String.
  2. Step 2: Verify other methods

    setSubject() accepts String, compact() is correctly called last, and Jwts.builder() is valid.
  3. Final Answer:

    signWith() requires a Key object, not a String -> Option C
  4. Quick Check:

    signWith() needs Key, not String [OK]
Hint: Use Key object with signWith(), not plain String [OK]
Common Mistakes:
  • Passing String directly to signWith()
  • Calling compact() too early
  • Misunderstanding setSubject() input
5. You want to generate a JWT in Spring Boot that expires in 10 minutes. Which code snippet correctly sets the expiration time using jjwt?
hard
A. Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact();
B. Jwts.builder().setSubject("user").setExpiry(600000).signWith(secretKey).compact();
C. Jwts.builder().setSubject("user").setExpiration(600000).signWith(secretKey).compact();
D. Jwts.builder().setSubject("user").setExpiresAt(new Date(600000)).signWith(secretKey).compact();

Solution

  1. Step 1: Understand expiration setting in jjwt

    setExpiration() expects a Date object representing the expiration time.
  2. Step 2: Calculate expiration time

    Use current time plus 600000 milliseconds (10 minutes) to set expiration correctly.
  3. Step 3: Check options

    Only Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); correctly uses setExpiration() with new Date(System.currentTimeMillis() + 600000).
  4. Final Answer:

    Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); -> Option A
  5. Quick Check:

    setExpiration(Date) with currentTime + 10min = Jwts.builder().setSubject("user").setExpiration(new Date(System.currentTimeMillis() + 600000)).signWith(secretKey).compact(); [OK]
Hint: Use setExpiration(new Date(System.currentTimeMillis() + millis)) [OK]
Common Mistakes:
  • Using setExpiry() or setExpiresAt() which don't exist
  • Passing milliseconds directly instead of Date
  • Setting expiration to a fixed past date