Bird
Raised Fist0
Spring Bootframework~10 mins

JWT vs session-based decision in Spring Boot - Visual Side-by-Side Comparison

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
Concept Flow - JWT vs session-based decision
User logs in
Decision: Use JWT or Session?
JWT
Create JWT
Send JWT
Client stores JWT
Client sends JWT with requests
Server verifies JWT
Access granted or denied
Logout or Expire
This flow shows how after login, the system chooses JWT or session, then creates and sends tokens, client stores and sends them back, and server verifies to allow access.
Execution Sample
Spring Boot
POST /login
if (useJWT) {
  create JWT token
  send token to client
} else {
  create session
  send session ID
}
This code decides on login whether to create a JWT or a session, then sends the appropriate token to the client.
Execution Table
StepActionDecisionToken CreatedToken SentClient StoresServer StoresVerification on Request
1User submits loginN/AN/AN/AN/AN/AN/A
2Check config for token typeUse JWTJWT token createdJWT sentJWT storedNo session storedJWT verified
3Client sends request with tokenUse JWTN/AN/AJWT sent with requestN/AJWT verified
4Access grantedUse JWTN/AN/AN/AN/AJWT valid
5User logs out or token expiresUse JWTN/AN/AJWT removedN/AAccess denied if token invalid
6Check config for token typeUse SessionSession createdSession ID sentSession ID storedSession storedSession checked
7Client sends request with session IDUse SessionN/AN/ASession ID sent with requestN/ASession checked
8Access grantedUse SessionN/AN/AN/AN/ASession valid
9User logs out or session expiresUse SessionN/AN/ASession ID removedSession removedAccess denied if session invalid
💡 Process ends when user logs out or token/session expires, denying further access.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5After Step 6After Step 7After Step 9
useJWTtrue or falsetrue or falsetrue or falsetrue or falsetrue or falsetrue or falsetrue or false
tokennullJWT token or nullJWT tokennull (removed)nullnullnull
sessionIDnullnullnullnullsession ID or nullsession IDnull (removed)
clientStorageemptyJWT stored or emptyJWT sent with requestsJWT removedSession ID stored or emptySession ID sentSession ID removed
serverStorageemptyNo session storedNo session storedNo session storedSession storedSession storedSession removed
Key Moments - 3 Insights
Why does JWT not require server to store session data?
Because JWT contains all user info and is verified by signature, the server just checks the token validity (see execution_table rows 2 and 3).
How does session-based auth keep track of users?
The server stores session data linked to a session ID sent to the client, which the client sends back on requests (see execution_table rows 6 and 7).
What happens when a JWT expires compared to a session?
JWT becomes invalid and access is denied without server state change; session expiration requires server to remove session data (see execution_table rows 5 and 9).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the client send the JWT with requests?
AStep 3
BStep 2
CStep 6
DStep 7
💡 Hint
Check the 'Client Stores' and 'Verification on Request' columns in execution_table row 3.
According to variable_tracker, what happens to the 'token' variable after step 5?
AIt remains the same JWT token
BIt is removed (null)
CIt changes to a session ID
DIt is stored on the server
💡 Hint
Look at the 'token' row and the value under 'After Step 5' in variable_tracker.
If the system uses session-based auth, at which step is the session ID sent to the client?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Refer to execution_table row 6 under 'Token Sent' column.
Concept Snapshot
JWT vs Session Decision in Spring Boot:
- After login, decide: JWT or Session
- JWT: create token, send to client, client stores and sends with requests
- Session: create server session, send session ID, client sends ID with requests
- Server verifies token or session on each request
- Logout or expiry ends access
- JWT is stateless; Session requires server storage
Full Transcript
This visual execution shows the decision process between JWT and session-based authentication in Spring Boot. When a user logs in, the system decides whether to use JWT or session. If JWT is chosen, a token is created and sent to the client, who stores it and sends it with each request. The server verifies the token without storing session data. If session is chosen, the server creates a session and sends a session ID to the client, who sends it back with requests. The server stores session data and checks it on each request. Access is granted if verification passes. Logout or token/session expiry ends access. Variables like token and sessionID change accordingly during the process. Key confusions include why JWT is stateless, how sessions track users, and what happens on expiry. The quiz tests understanding of these steps and variable changes.

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