Bird
Raised Fist0
Spring Bootframework~20 mins

Stateless authentication mental model 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
🎖️
Stateless Authentication Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Stateless Authentication Tokens
In a stateless authentication system using JWTs (JSON Web Tokens), what happens when a user logs out?
AThe server deletes the token from its session store to invalidate it.
BThe server sends a new token with a logout flag to the client.
CThe server marks the token as expired in a centralized database.
DThe client deletes the token locally, and the server does not store any session data.
Attempts:
2 left
💡 Hint

Think about what 'stateless' means for the server's role in managing sessions.

component_behavior
intermediate
2:00remaining
Token Validation in Stateless Authentication
Given a Spring Boot REST API using stateless JWT authentication, what is the server's behavior when it receives a request with an expired token?
AThe server rejects the request with an unauthorized error without checking any session.
BThe server refreshes the token automatically and processes the request.
CThe server looks up the token in a session store to verify expiration.
DThe server ignores the token and allows the request to proceed.
Attempts:
2 left
💡 Hint

Remember that stateless means no session store on the server.

📝 Syntax
advanced
2:30remaining
Correct JWT Filter Configuration in Spring Boot
Which of the following Spring Boot filter configurations correctly implements stateless JWT authentication by validating tokens on each request?
Spring Boot
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = extractToken(request);
        if (token != null && validateToken(token)) {
            UsernamePasswordAuthenticationToken auth = getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(request, response);
    }
}
AAdd the filter with session management set to IF_REQUIRED and enable CSRF.
BAdd the filter with session management set to ALWAYS and disable CSRF.
CAdd the filter with session management set to STATELESS and disable CSRF.
DAdd the filter without configuring session management or CSRF.
Attempts:
2 left
💡 Hint

Stateless authentication requires no server session and CSRF protection is usually disabled for APIs.

🔧 Debug
advanced
2:30remaining
Identifying the Cause of Token Rejection
A Spring Boot app using stateless JWT authentication rejects all valid tokens with an unauthorized error. Which code snippet is the most likely cause?
Spring Boot
public boolean validateToken(String token) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        return true;
    } catch (ExpiredJwtException e) {
        return false;
    } catch (JwtException e) {
        return false;
    }
}
AThe filter does not call filterChain.doFilter after validation.
BThe secretKey used to parse tokens is different from the one used to sign them.
CThe token is not extracted from the Authorization header correctly.
DThe validateToken method does not catch all exceptions and crashes.
Attempts:
2 left
💡 Hint

Check if the key used to verify tokens matches the signing key.

lifecycle
expert
3:00remaining
Stateless Authentication Token Expiry and Refresh Flow
In a stateless JWT authentication system, which sequence correctly describes the lifecycle of token expiry and refresh to maintain user access without server session storage?
A1, 2, 3, 4
B1, 3, 2, 4
C2, 1, 3, 4
D1, 2, 4, 3
Attempts:
2 left
💡 Hint

Think about the order of client requests and server validations in token refresh.

Practice

(1/5)
1. What is the main idea behind stateless authentication in Spring Boot?
easy
A. The server does not keep user session data; clients send tokens each time.
B. The server stores all user sessions in memory for quick access.
C. The server uses cookies to remember users between requests.
D. The server requires users to log in for every single request manually.

Solution

  1. Step 1: Understand stateless authentication concept

    Stateless means the server does not save any user session data between requests.
  2. Step 2: Identify how user identity is maintained

    Clients send a token with each request to prove who they are without server memory.
  3. Final Answer:

    The server does not keep user session data; clients send tokens each time. -> Option A
  4. Quick Check:

    Stateless = No server session, token sent each time [OK]
Hint: Stateless means no server memory, token sent every request [OK]
Common Mistakes:
  • Thinking server stores session data
  • Confusing cookies with stateless tokens
  • Assuming login required every request
2. Which of the following is the correct way to send a token in a stateless Spring Boot API request?
easy
A. Include the token in the request body as plain text.
B. Send the token in the Authorization header as a Bearer token.
C. Store the token in a server-side session variable.
D. Attach the token as a URL query parameter without encoding.

Solution

  1. Step 1: Recall token transmission best practice

    Tokens are usually sent in the Authorization header using the Bearer scheme.
  2. Step 2: Eliminate incorrect methods

    Request body is not standard for tokens; server-side session breaks statelessness; URL query parameters are insecure and not recommended.
  3. Final Answer:

    Send the token in the Authorization header as a Bearer token. -> Option B
  4. Quick Check:

    Token in Authorization header = correct [OK]
Hint: Tokens go in Authorization header as Bearer [OK]
Common Mistakes:
  • Putting token in request body
  • Using server session storage
  • Sending token in URL query insecurely
3. Given this Spring Boot controller snippet using stateless authentication:
@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);
    if (token.equals("valid-token")) {
        return ResponseEntity.ok("User Profile Data");
    } else {
        return ResponseEntity.status(403).body("Forbidden");
    }
}

What will be the response if the client sends header Authorization: Bearer valid-token?
medium
A. 401 Unauthorized
B. 403 Forbidden
C. 200 OK with 'User Profile Data'
D. 500 Internal Server Error

Solution

  1. Step 1: Check Authorization header presence and format

    The header is present and starts with "Bearer ", so it passes the first check.
  2. Step 2: Extract token and compare

    The token extracted is "valid-token", which matches the expected valid token.
  3. Step 3: Determine response

    Since token is valid, the method returns 200 OK with "User Profile Data".
  4. Final Answer:

    200 OK with 'User Profile Data' -> Option C
  5. Quick Check:

    Valid token = 200 OK response [OK]
Hint: Valid Bearer token returns 200 OK [OK]
Common Mistakes:
  • Confusing 401 and 403 status codes
  • Ignoring token prefix check
  • Assuming server stores session
4. Identify the bug in this stateless authentication filter code snippet:
public boolean isValidToken(String token) {
    if (token == null || token.isEmpty()) {
        return false;
    }
    // Token validation logic
    return token.equals("valid-token");
}

public void doFilter(HttpServletRequest req, HttpServletResponse res) {
    String auth = req.getHeader("Authorization");
    if (auth != null && auth.startsWith("Bearer ")) {
        String token = auth.substring(7);
        if (!isValidToken(token)) {
            res.setStatus(401);
        }
    }
    // Continue filter chain
}

What is the main issue?
medium
A. Possible NullPointerException if Authorization header is missing
B. Token validation logic is incorrect
C. Response status code should be 403 instead of 401
D. Filter does not extract token correctly

Solution

  1. Step 1: Analyze header usage

    The original code calls auth.startsWith("Bearer ") without checking if auth is null.
  2. Step 2: Identify risk

    If Authorization header is missing, auth is null, so calling startsWith causes NullPointerException.
  3. Final Answer:

    Possible NullPointerException if Authorization header is missing -> Option A
  4. Quick Check:

    Check null before startsWith to avoid error [OK]
Hint: Check for null before calling startsWith [OK]
Common Mistakes:
  • Assuming header always present
  • Mixing 401 and 403 status codes
  • Ignoring null safety in Java
5. In a stateless Spring Boot app using JWT tokens, which approach best supports scaling across multiple servers?
hard
A. Store user sessions in a shared database accessed by all servers.
B. Cache user sessions in server memory for faster access.
C. Use sticky sessions to keep users on the same server.
D. Validate JWT tokens on each request without server session storage.

Solution

  1. Step 1: Understand stateless scaling needs

    Scaling means any server can handle any request without shared session state.
  2. Step 2: Evaluate options

    Storing sessions in DB or memory adds state and complexity; sticky sessions tie users to one server, limiting scaling.
  3. Step 3: Identify best stateless method

    Validating JWT tokens on each request keeps servers stateless and allows easy scaling.
  4. Final Answer:

    Validate JWT tokens on each request without server session storage. -> Option D
  5. Quick Check:

    Stateless + JWT = validate token each request [OK]
Hint: Stateless scaling means no server session, validate tokens each time [OK]
Common Mistakes:
  • Using sticky sessions limits scaling
  • Storing sessions breaks statelessness
  • Caching sessions in memory causes sync issues