Bird
Raised Fist0
Spring Bootframework~20 mins

JWT vs session-based decision in Spring Boot - Practice Questions

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 vs Session Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
When to prefer JWT over session-based authentication?
Which scenario best justifies using JWT instead of session-based authentication in a Spring Boot application?
AYou want to store user data only on the server and keep tokens minimal.
BYou want to maintain server-side session state for each user to easily revoke access.
CYou want to rely on server memory to track user sessions for quick invalidation.
DYou need a stateless authentication mechanism that works well with multiple microservices.
Attempts:
2 left
💡 Hint
Think about whether the authentication needs to be stateless or stateful.
component_behavior
intermediate
2:00remaining
Effect of token expiration in JWT vs session
In a Spring Boot app using JWT, what happens when the JWT token expires compared to session expiration in session-based authentication?
AJWT tokens never expire; session expiration depends on client-side cookie settings.
BJWT token expiration forces client to get a new token; session expiration requires server to clear session data.
CJWT token expiration automatically refreshes the token; session expiration logs out the user immediately.
DJWT token expiration clears server session; session expiration invalidates JWT tokens.
Attempts:
2 left
💡 Hint
Consider where the expiration is checked and who manages it.
🔧 Debug
advanced
2:30remaining
Why does a Spring Boot app reject a valid JWT token?
Given a Spring Boot app using JWT authentication, which option explains why a valid JWT token might be rejected during request processing?
AThe token is expired but the server ignores expiration checks.
BThe token's signature algorithm does not match the server's expected algorithm.
CThe token is signed with the correct key but the server's clock is ahead causing premature expiration.
DThe token payload is missing the 'sub' claim but the server does not require it.
Attempts:
2 left
💡 Hint
Think about time synchronization between client and server.
state_output
advanced
2:30remaining
Session state behavior after server restart
What happens to user sessions in a Spring Boot app using session-based authentication if the server restarts without session persistence?
AAll user sessions are lost and users must log in again.
BSessions remain active because they are stored in client cookies.
CSessions are automatically restored from JWT tokens stored on the client.
DOnly sessions with 'remember me' enabled are preserved.
Attempts:
2 left
💡 Hint
Consider where session data is stored and what happens on server restart.
📝 Syntax
expert
3:00remaining
Correct JWT filter configuration in Spring Boot
Which code snippet correctly configures a JWT authentication filter in a Spring Boot security filter chain?
Spring Boot
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
        )
        .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
        .build();
}
AAdd the JWT filter before UsernamePasswordAuthenticationFilter to process token before username/password checks.
BAdd the JWT filter replacing UsernamePasswordAuthenticationFilter to avoid duplicate authentication.
CAdd the JWT filter as the last filter in the chain to catch all requests after authentication.
DAdd the JWT filter after UsernamePasswordAuthenticationFilter to ensure authentication happens first.
Attempts:
2 left
💡 Hint
Think about when the JWT token should be checked relative to username/password authentication.

Practice

(1/5)
1. Which statement best describes JWT authentication in Spring Boot?
easy
A. User info is stored on the server and tracked with cookies.
B. User info is stored only in the database without tokens or sessions.
C. User info is stored in a token sent with each request, no server storage needed.
D. User info is stored in browser local storage only.

Solution

  1. Step 1: Understand JWT storage method

    JWT stores user information inside a token that is sent with every request, so the server does not need to keep session data.
  2. Step 2: Compare with session storage

    Sessions store user info on the server and use cookies to track users, unlike JWT which is stateless.
  3. Final Answer:

    User info is stored in a token sent with each request, no server storage needed. -> Option C
  4. Quick Check:

    JWT = token-based stateless auth [OK]
Hint: JWT stores info in tokens, sessions store on server [OK]
Common Mistakes:
  • Confusing JWT with session storage
  • Thinking JWT requires server-side storage
  • Believing JWT info is only in browser storage
2. Which code snippet correctly sets a session attribute in Spring Boot?
easy
A. request.getSession().setAttribute("user", userObject);
B. request.setSessionAttribute("user", userObject);
C. session.setAttribute("user", userObject);
D. request.session().setAttribute("user", userObject);

Solution

  1. Step 1: Recall correct method to get session

    In Spring Boot, you get the session from the request using request.getSession().
  2. Step 2: Set attribute on session object

    Then call setAttribute("user", userObject) on the session to store data.
  3. Final Answer:

    request.getSession().setAttribute("user", userObject); -> Option A
  4. Quick Check:

    Use getSession() then setAttribute() [OK]
Hint: Use request.getSession() before setAttribute [OK]
Common Mistakes:
  • Calling setAttribute directly on request
  • Using incorrect method names like setSessionAttribute
  • Trying to call session() as a method on request
3. Given this Spring Boot code snippet using JWT, what is the expected behavior?
String token = jwtUtil.generateToken(userDetails);
response.setHeader("Authorization", "Bearer " + token);
// No session is created on server
medium
A. User info is stored on server session and token is ignored.
B. Token is sent to client; server remains stateless without session.
C. Session is created on server with token stored inside.
D. Token is stored in server memory for each user.

Solution

  1. Step 1: Analyze token generation and response header

    The code generates a JWT token and sends it in the Authorization header to the client.
  2. Step 2: Note server session behavior

    The comment says no session is created on the server, meaning the server stays stateless.
  3. Final Answer:

    Token is sent to client; server remains stateless without session. -> Option B
  4. Quick Check:

    JWT = stateless token sent to client [OK]
Hint: JWT sends token, no server session created [OK]
Common Mistakes:
  • Assuming server stores token in session
  • Thinking token is ignored by server
  • Believing token is stored in server memory
4. Identify the error in this Spring Boot session code snippet:
HttpSession session = request.getSession(false);
session.setAttribute("user", userObject);
medium
A. Session attributes cannot store user objects.
B. setAttribute method does not exist on HttpSession.
C. request.getSession(false) always creates a new session.
D. Using getSession(false) may return null causing NullPointerException.

Solution

  1. Step 1: Understand getSession(false) behavior

    getSession(false) returns existing session or null if none exists; it does not create a new session.
  2. Step 2: Check for possible null usage

    If session is null, calling setAttribute causes NullPointerException.
  3. Final Answer:

    Using getSession(false) may return null causing NullPointerException. -> Option D
  4. Quick Check:

    getSession(false) can return null [OK]
Hint: getSession(false) may return null, check before use [OK]
Common Mistakes:
  • Assuming getSession(false) always returns a session
  • Believing setAttribute is invalid method
  • Thinking sessions cannot store objects
5. You are building a Spring Boot app that must scale across many servers without sticky sessions. Which authentication method should you choose and why?
hard
A. Use JWT because it is stateless and does not require server session storage.
B. Use JWT but store tokens in server memory for faster access.
C. Use session-based authentication with distributed cache to share sessions.
D. Use session-based authentication because it stores user info on the server.

Solution

  1. Step 1: Understand scaling needs

    Scaling across many servers without sticky sessions means no single server holds user session data.
  2. Step 2: Compare authentication methods

    Session-based auth stores user info on server, requiring session sharing or sticky sessions, which complicates scaling.
  3. Step 3: Choose JWT for statelessness

    JWT stores user info in tokens sent with requests, so servers remain stateless and scaling is easier.
  4. Final Answer:

    Use JWT because it is stateless and does not require server session storage. -> Option A
  5. Quick Check:

    Stateless JWT best for scalable multi-server apps [OK]
Hint: Stateless JWT fits multi-server scaling best [OK]
Common Mistakes:
  • Choosing sessions without sticky sessions or shared cache
  • Thinking JWT requires server memory storage
  • Ignoring stateless benefits of JWT