Choosing between JWT and session-based authentication helps decide how your app keeps users logged in safely and easily.
JWT vs session-based decision in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Spring Boot
JWT: Token is created and sent to client; client sends token with each request. Session: Server stores user info; client keeps session ID cookie.
JWT tokens are self-contained and stateless.
Sessions require server memory or storage to keep user data.
Examples
Spring Boot
JWT example: // Server creates token String token = Jwts.builder() .setSubject(username) .setExpiration(new Date(System.currentTimeMillis() + 86400000)) .signWith(secretKey) .compact(); // Client sends token in Authorization header Authorization: Bearer <token>
Spring Boot
Session example:
// Server creates session
HttpSession session = request.getSession();
session.setAttribute("user", userObject);
// Client sends session ID cookie automatically
Cookie: JSESSIONID=abc123Sample Program
This Spring Boot app shows session-based login. When you visit /login, it saves user info in the session. Then /profile shows the logged-in user.
Spring Boot
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpSession; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class SessionController { @GetMapping("/login") public String login(HttpSession session) { session.setAttribute("user", "Alice"); return "User logged in with session ID: " + session.getId(); } @GetMapping("/profile") public String profile(HttpSession session) { Object user = session.getAttribute("user"); if (user == null) { return "No user logged in."; } return "User profile for: " + user; } }
Important Notes
JWT is good for apps needing scalability and statelessness.
Sessions are simpler for apps running on a single server.
Always protect tokens and session IDs with HTTPS to keep users safe.
Summary
JWT stores user info in a token sent with each request, no server storage needed.
Sessions store user info on the server and track users with cookies.
Choose JWT for scalable, stateless apps; choose sessions for simpler, single-server apps.
Practice
1. Which statement best describes JWT authentication in Spring Boot?
easy
Solution
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.Step 2: Compare with session storage
Sessions store user info on the server and use cookies to track users, unlike JWT which is stateless.Final Answer:
User info is stored in a token sent with each request, no server storage needed. -> Option CQuick 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
Solution
Step 1: Recall correct method to get session
In Spring Boot, you get the session from the request usingrequest.getSession().Step 2: Set attribute on session object
Then callsetAttribute("user", userObject)on the session to store data.Final Answer:
request.getSession().setAttribute("user", userObject); -> Option AQuick 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 servermedium
Solution
Step 1: Analyze token generation and response header
The code generates a JWT token and sends it in the Authorization header to the client.Step 2: Note server session behavior
The comment says no session is created on the server, meaning the server stays stateless.Final Answer:
Token is sent to client; server remains stateless without session. -> Option BQuick 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
Solution
Step 1: Understand getSession(false) behavior
getSession(false) returns existing session or null if none exists; it does not create a new session.Step 2: Check for possible null usage
If session is null, calling setAttribute causes NullPointerException.Final Answer:
Using getSession(false) may return null causing NullPointerException. -> Option DQuick 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
Solution
Step 1: Understand scaling needs
Scaling across many servers without sticky sessions means no single server holds user session data.Step 2: Compare authentication methods
Session-based auth stores user info on server, requiring session sharing or sticky sessions, which complicates scaling.Step 3: Choose JWT for statelessness
JWT stores user info in tokens sent with requests, so servers remain stateless and scaling is easier.Final Answer:
Use JWT because it is stateless and does not require server session storage. -> Option AQuick 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
