Bird
Raised Fist0
Spring Bootframework~20 mins

Why JWT matters for APIs in Spring Boot - Challenge Your Understanding

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 API Security Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the primary purpose of JWT in API security?
Consider a Spring Boot API that uses JWT for authentication. What is the main reason JWT is used in this context?
ATo store user passwords safely on the client side
BTo encrypt all API data so only the server can read it
CTo replace HTTPS for secure communication
DTo securely transmit user identity and claims between client and server without storing session state on the server
Attempts:
2 left
💡 Hint

Think about how JWT helps avoid server-side session storage.

component_behavior
intermediate
2:00remaining
How does a Spring Boot API behave when receiving an expired JWT?
In a Spring Boot API secured with JWT, what happens when a client sends a request with an expired JWT token?
AThe API rejects the request with a 401 Unauthorized error
BThe API accepts the request but logs a warning
CThe API refreshes the token automatically and processes the request
DThe API ignores the token and treats the request as anonymous
Attempts:
2 left
💡 Hint

Think about how JWT expiration affects authentication.

📝 Syntax
advanced
2:30remaining
Identify the correct way to extract claims from a JWT in Spring Boot
Given the following code snippet to parse a JWT token, which option correctly extracts the 'username' claim?
Spring Boot
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
Claims claims = Jwts.parserBuilder()
    .setSigningKey(secretKey)
    .build()
    .parseClaimsJws(token)
    .getBody();
// Extract username here
AString username = claims.get("username", String.class);
BString username = claims.getSubject();
CString username = claims.get("user", String.class);
DString username = claims.getIssuer();
Attempts:
2 left
💡 Hint

JWT standard uses a specific claim for the principal subject.

state_output
advanced
2:00remaining
What is the effect of missing JWT in a secured Spring Boot API request?
If a client sends a request to a Spring Boot API endpoint secured with JWT but does not include any JWT token, what will be the API's response?
AThe API processes the request as an anonymous user
BThe API responds with 403 Forbidden error
CThe API responds with 401 Unauthorized error
DThe API redirects the client to a login page
Attempts:
2 left
💡 Hint

Think about how Spring Security handles missing authentication tokens.

🔧 Debug
expert
3:00remaining
Why does this Spring Boot JWT validation code fail to reject tampered tokens?
Examine this JWT validation snippet in a Spring Boot API: String token = request.getHeader("Authorization").substring(7); Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Why might this code fail to reject a JWT token that has been tampered with?
ANot catching exceptions from parseClaimsJws allows tampered tokens to pass silently
BThe substring(7) call removes part of the token, causing parseClaimsJws to skip verification
CThe secretKey is not decoded properly before use, so signature verification fails silently
DUsing Jwts.parser() instead of Jwts.parserBuilder() causes the signature not to be verified properly
Attempts:
2 left
💡 Hint

Consider what happens if parseClaimsJws throws an exception and it is not handled.

Practice

(1/5)
1. Why is JWT important for APIs in Spring Boot?
easy
A. It replaces the need for HTTPS in API communication.
B. It stores user passwords in the token for quick access.
C. It securely identifies users without storing session data on the server.
D. It automatically encrypts all API responses.

Solution

  1. Step 1: Understand JWT's role in user identification

    JWT carries user identity information inside the token, so the server does not need to keep session data.
  2. Step 2: Recognize security benefits

    This stateless approach improves security and scalability by avoiding server-side session storage.
  3. Final Answer:

    It securely identifies users without storing session data on the server. -> Option C
  4. Quick Check:

    JWT = stateless secure user ID [OK]
Hint: JWT carries user info, no server session needed [OK]
Common Mistakes:
  • Thinking JWT stores passwords inside the token
  • Believing JWT replaces HTTPS
  • Assuming JWT encrypts API responses automatically
2. Which of the following is the correct way to include a JWT in an HTTP request header?
easy
A. Auth-Token: <token>
B. Authorization: Bearer <token>
C. Token: JWT <token>
D. JWT-Authorization: Bearer <token>

Solution

  1. Step 1: Recall standard JWT header format

    The standard way to send JWTs is in the Authorization header with the Bearer scheme.
  2. Step 2: Match the correct syntax

    "Authorization: Bearer <token>" is the correct and widely accepted format.
  3. Final Answer:

    Authorization: Bearer <token> -> Option B
  4. Quick Check:

    JWT header = Authorization: Bearer [OK]
Hint: JWT goes in Authorization header with Bearer prefix [OK]
Common Mistakes:
  • Using non-standard header names like Token or Auth-Token
  • Omitting the Bearer prefix
  • Adding extra words like JWT-Authorization
3. Given this Spring Boot controller method snippet, what will happen if the JWT is missing or invalid?
@GetMapping("/profile")
public ResponseEntity<String> getProfile(@RequestHeader("Authorization") String authHeader) {
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        return ResponseEntity.status(401).body("Unauthorized");
    }
    String token = authHeader.substring(7);
    // Assume validateToken returns false if token invalid
    if (!jwtService.validateToken(token)) {
        return ResponseEntity.status(401).body("Unauthorized");
    }
    return ResponseEntity.ok("User profile data");
}
medium
A. Returns 500 Internal Server Error on invalid JWT.
B. Returns 200 OK with user profile regardless of JWT.
C. Throws a NullPointerException if JWT is missing.
D. Returns 401 Unauthorized if JWT is missing or invalid.

Solution

  1. Step 1: Check handling of missing or malformed Authorization header

    The code returns 401 Unauthorized if the header is missing or does not start with "Bearer ".
  2. Step 2: Check token validation logic

    If the token is invalid, the method also returns 401 Unauthorized.
  3. Final Answer:

    Returns 401 Unauthorized if JWT is missing or invalid. -> Option D
  4. Quick Check:

    Missing/invalid JWT = 401 Unauthorized [OK]
Hint: Missing or bad JWT triggers 401 Unauthorized [OK]
Common Mistakes:
  • Assuming it returns 200 OK without JWT
  • Expecting exceptions instead of 401 response
  • Thinking it returns 500 error on invalid token
4. Identify the bug in this Spring Boot JWT filter snippet:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String authHeader = req.getHeader("Authorization");
    if (authHeader != null && authHeader.startsWith("Bearer ")) {
        String token = authHeader.substring(7);
        if (jwtService.validateToken(token)) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
    }
    chain.doFilter(request, response);
}
medium
A. It sets authentication to null instead of a valid Authentication object.
B. It does not check if authHeader is null before substring.
C. It calls chain.doFilter before validating the token.
D. It uses the wrong header name for JWT.

Solution

  1. Step 1: Analyze authentication setting logic

    The code sets authentication to null even when the token is valid, which means no user is authenticated.
  2. Step 2: Understand correct behavior

    It should set a valid Authentication object to represent the logged-in user, not null.
  3. Final Answer:

    It sets authentication to null instead of a valid Authentication object. -> Option A
  4. Quick Check:

    Valid token must set Authentication, not null [OK]
Hint: Valid token must set Authentication object, not null [OK]
Common Mistakes:
  • Ignoring that authentication is set to null
  • Thinking substring without null check causes error here
  • Assuming chain.doFilter order is wrong
  • Believing header name is incorrect
5. You want your Spring Boot API to allow users to stay logged in without server sessions, using JWT. Which approach best achieves this while keeping the API stateless and secure?
hard
A. Generate a JWT after login containing user info, send it to client, and require it in Authorization header for each request.
B. Store user sessions in a database and send session IDs in cookies to clients.
C. Send user credentials with every API request and validate each time on the server.
D. Use JWT only for login, then switch to server sessions for other requests.

Solution

  1. Step 1: Understand stateless authentication with JWT

    JWT tokens carry user info and are sent by clients with each request, so the server does not store session data.
  2. Step 2: Compare with other methods

    Storing sessions or sending credentials every time breaks statelessness or security best practices.
  3. Final Answer:

    Generate a JWT after login containing user info, send it to client, and require it in Authorization header for each request. -> Option A
  4. Quick Check:

    JWT = stateless secure token per request [OK]
Hint: JWT tokens keep API stateless and secure per request [OK]
Common Mistakes:
  • Using server sessions instead of JWT for statelessness
  • Sending credentials on every request
  • Switching between JWT and sessions inconsistently