Bird
Raised Fist0
Spring Bootframework~20 mins

Authentication with JWT token 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 Authentication Master
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 token validation method?
Consider this Spring Boot method that validates a JWT token. What will be the returned value if the token is expired?
Spring Boot
public boolean validateToken(String token) {
    try {
        Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        return true;
    } catch (ExpiredJwtException e) {
        return false;
    } catch (JwtException e) {
        return false;
    }
}
Afalse
BThrows ExpiredJwtException
Ctrue
Dnull
Attempts:
2 left
💡 Hint
Think about what happens when the token is expired and how exceptions are handled.
📝 Syntax
intermediate
2:00remaining
Which option correctly creates a JWT token with a subject and expiration?
Select the code snippet that correctly creates a JWT token with subject "user123" and expiration 1 hour from now using jjwt library.
AString token = Jwts.builder().setSubject("user123").setExpiration(new Date(System.currentTimeMillis() + 3600000)).signWith(key).compact();
BString token = Jwts.builder().setSubject("user123").setExpiration(System.currentTimeMillis() + 3600000).signWith(key).compact();
CString token = Jwts.builder().setSubject("user123").setExpiration(new Date().getTime() + 3600000).signWith(key).compact();
DString token = Jwts.builder().setSubject("user123").setExpiration(new Date(System.currentTimeMillis() - 3600000)).signWith(key).compact();
Attempts:
2 left
💡 Hint
Expiration requires a Date object representing a future time.
🔧 Debug
advanced
2:00remaining
Why does this JWT token parsing code throw a SignatureException?
Given this code snippet, why does parsing the JWT token throw a SignatureException?
Spring Boot
Jwts.parserBuilder().setSigningKey(wrongKey).build().parseClaimsJws(token);
AThe token is null or empty.
BThe token is expired and cannot be parsed.
CThe token format is invalid and missing parts.
DThe signing key used to parse the token does not match the key used to sign it.
Attempts:
2 left
💡 Hint
Think about what the signature in JWT ensures.
state_output
advanced
2:00remaining
What is the value of 'username' after extracting from this JWT token?
Assuming the JWT token contains a claim 'sub' with value 'alice', what will be the value of 'username' after this code runs?
Spring Boot
Claims claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
String username = claims.getSubject();
Anull
B"alice"
CThrows NullPointerException
D"sub"
Attempts:
2 left
💡 Hint
The 'sub' claim is accessed by getSubject() method.
🧠 Conceptual
expert
2:00remaining
Which statement best explains why JWT tokens are stateless in authentication?
Why are JWT tokens considered stateless in authentication systems?
ABecause the server stores all tokens in a database to track user sessions.
BBecause JWT tokens expire immediately after creation, forcing re-authentication.
CBecause all user information and claims are stored inside the token itself, so no server-side session storage is needed.
DBecause JWT tokens require a server to validate each token against a session store.
Attempts:
2 left
💡 Hint
Think about where the user data lives in JWT authentication.

Practice

(1/5)
1. What is the main purpose of using a JWT token in Spring Boot authentication?
easy
A. To store user passwords in the database
B. To securely transmit user identity without sending passwords every time
C. To encrypt the entire application data
D. To replace the need for HTTPS

Solution

  1. Step 1: Understand JWT token role

    JWT tokens are used to prove user identity securely without resending passwords.
  2. Step 2: Compare options with JWT purpose

    Only To securely transmit user identity without sending passwords every time correctly describes this purpose; others are unrelated or incorrect.
  3. Final Answer:

    To securely transmit user identity without sending passwords every time -> Option B
  4. Quick Check:

    JWT token purpose = secure identity proof [OK]
Hint: JWT tokens prove identity without passwords [OK]
Common Mistakes:
  • Thinking JWT stores passwords
  • Confusing JWT with data encryption
  • Assuming JWT replaces HTTPS
2. Which of the following is the correct way to extract the JWT token from an HTTP request header in Spring Boot?
easy
A. String token = request.getParameter("Authorization");
B. String token = request.getCookie("jwt");
C. String token = request.getBody();
D. String token = request.getHeader("Authorization").substring(7);

Solution

  1. Step 1: Identify JWT token location in HTTP request

    JWT tokens are usually sent in the Authorization header with prefix "Bearer ".
  2. Step 2: Extract token correctly

    String token = request.getHeader("Authorization").substring(7); extracts the header and removes the "Bearer " prefix (7 characters), which is correct.
  3. Final Answer:

    String token = request.getHeader("Authorization").substring(7); -> Option D
  4. Quick Check:

    Extract JWT from Authorization header [OK]
Hint: JWT is in Authorization header with 'Bearer ' prefix [OK]
Common Mistakes:
  • Using request parameters instead of headers
  • Trying to get token from request body
  • Assuming token is in cookies by default
3. Given this Spring Boot JWT validation snippet, what will be the output if the token is expired?
try {
  Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
  System.out.println("Token is valid");
} catch (ExpiredJwtException e) {
  System.out.println("Token expired");
} catch (JwtException e) {
  System.out.println("Invalid token");
}
medium
A. Invalid token
B. Token is valid
C. Token expired
D. No output

Solution

  1. Step 1: Understand exception handling in JWT parsing

    If the token is expired, the parser throws ExpiredJwtException, caught by the first catch block.
  2. Step 2: Identify printed output for expired token

    The catch block prints "Token expired" when ExpiredJwtException occurs.
  3. Final Answer:

    Token expired -> Option C
  4. Quick Check:

    Expired token triggers ExpiredJwtException [OK]
Hint: ExpiredJwtException means token expired [OK]
Common Mistakes:
  • Confusing expired token with invalid token
  • Ignoring exception handling order
  • Assuming no output on exceptions
4. Identify the error in this JWT token generation code snippet in Spring Boot:
String token = Jwts.builder()
  .setSubject(username)
  .signWith(SignatureAlgorithm.HS256, secretKey)
  .compact();
medium
A. Incorrect method to set signing key in new jjwt versions
B. Missing call to build() before compact()
C. Username should not be set as subject
D. Missing token expiration setting

Solution

  1. Step 1: Check jjwt signing method usage

    In recent jjwt versions, signWith requires a Key object, not just algorithm and string key.
  2. Step 2: Identify correct signing method

    Using signWith(SignatureAlgorithm, String) is deprecated and causes errors; must use signWith(Key).
  3. Final Answer:

    Incorrect method to set signing key in new jjwt versions -> Option A
  4. Quick Check:

    Use Key object with signWith in jjwt [OK]
Hint: Use Key object, not algorithm + string, in signWith [OK]
Common Mistakes:
  • Ignoring jjwt version changes
  • Assuming string key is accepted directly
  • Confusing expiration with signing errors
5. You want to implement JWT authentication in Spring Boot that automatically rejects tokens older than 15 minutes and refreshes tokens on each valid request. Which approach correctly combines expiration and refresh logic?
hard
A. Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request
B. Set token expiration to 15 minutes and never refresh tokens; force user to login again after expiry
C. Set token expiration to 1 hour and refresh tokens only when user logs out
D. Do not set expiration and refresh tokens every time to keep user logged in indefinitely

Solution

  1. Step 1: Understand token expiration and refresh needs

    To reject tokens older than 15 minutes, set expiration to 15 minutes.
  2. Step 2: Implement refresh on each valid request

    Issuing a new token with updated expiration on each valid request keeps user session active securely.
  3. Final Answer:

    Set token expiration to 15 minutes and issue a new token with updated expiration on each valid request -> Option A
  4. Quick Check:

    Short expiration + refresh token = secure session [OK]
Hint: Short expiration plus refresh token on requests [OK]
Common Mistakes:
  • Not refreshing tokens causing forced logouts
  • Setting too long expiration risking security
  • Ignoring expiration causing infinite sessions