Bird
Raised Fist0
Spring Bootframework~15 mins

JWT vs session-based decision in Spring Boot - Trade-offs & Expert Analysis

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
Overview - JWT vs session-based decision
What is it?
JWT (JSON Web Token) and session-based authentication are two ways to keep track of who a user is after they log in. JWT uses a token that the server gives to the user, which the user sends back with each request. Session-based authentication stores user information on the server and uses a session ID cookie to identify the user. Both help websites remember users without asking them to log in every time.
Why it matters
Without a way to remember users, websites would ask for login details on every page, making the experience frustrating. Choosing between JWT and session-based authentication affects security, performance, and how easy it is to scale the application. Picking the wrong method can cause security risks or slow down the app, so understanding the difference helps build better, safer software.
Where it fits
Before learning this, you should understand basic web concepts like HTTP requests, cookies, and user authentication. After this, you can explore advanced security topics like OAuth, OpenID Connect, and how to implement authentication in distributed systems or microservices.
Mental Model
Core Idea
JWT stores user identity in a self-contained token sent with each request, while session-based authentication keeps user data on the server and uses a session ID to track users.
Think of it like...
Imagine a concert: JWT is like a ticket with all your info printed on it that you show at every entrance, while session-based is like a wristband given at the entrance that the staff checks against their list inside.
┌───────────────┐          ┌───────────────┐
│   Client      │          │   Server      │
└──────┬────────┘          └──────┬────────┘
       │                           │
       │ 1. Login request          │
       │──────────────────────────>│
       │                           │
       │ 2a. Server creates JWT    │
       │     or session entry      │
       │                           │
       │ 2b. Server sends JWT      │
       │     or session cookie     │
       │<──────────────────────────│
       │                           │
       │ 3. Client sends JWT       │
       │    or session cookie      │
       │    with each request      │
       │──────────────────────────>│
       │                           │
       │ 4. Server verifies JWT    │
       │    or session ID          │
       │                           │
Build-Up - 6 Steps
1
FoundationBasics of User Authentication
🤔
Concept: Understanding how websites know who you are after you log in.
When you log into a website, it needs to remember you on later pages. This is done by sending some kind of proof with each request to show you are logged in. Without this, the website would treat every page visit as a new user.
Result
You learn that authentication means proving who you are, and the website needs a way to remember this proof between pages.
Understanding that authentication is about remembering identity across requests is the foundation for all login systems.
2
FoundationHow Sessions Work in Web Apps
🤔
Concept: Sessions store user info on the server and use a session ID cookie to track users.
When you log in, the server creates a session with your info and sends a cookie with a session ID to your browser. Your browser sends this cookie back with each request. The server looks up your session ID to find your info and knows you are logged in.
Result
You see that sessions keep data on the server and rely on cookies to identify users.
Knowing that sessions keep data server-side helps understand why servers need memory and can control user state centrally.
3
IntermediateJWT Structure and Usage
🤔Before reading on: Do you think JWT stores user data on the server or inside the token itself? Commit to your answer.
Concept: JWT is a token containing user info, signed by the server, sent to the client to send back with requests.
A JWT has three parts: header, payload, and signature. The payload contains user info like ID and roles. The signature ensures the token wasn't changed. The server does not store session data; it just verifies the token's signature on each request.
Result
You understand JWTs are self-contained tokens that prove identity without server storage.
Understanding JWTs carry their own data explains why servers can be stateless and scale easily.
4
IntermediateComparing State Management: Server vs Client
🤔Before reading on: Which do you think is easier to scale horizontally, sessions or JWT? Commit to your answer.
Concept: Sessions keep state on the server, JWT keeps state in the client token.
Sessions require the server to remember each user, which can be hard when many servers exist. JWTs let servers be stateless because the token has all info. But JWTs can grow large and can't be easily revoked.
Result
You see trade-offs: sessions need server memory but allow easy logout; JWTs scale well but have revocation challenges.
Knowing where state lives helps decide which method fits your app's scale and security needs.
5
AdvancedSecurity Considerations for JWT and Sessions
🤔Before reading on: Do you think JWTs are always more secure than sessions? Commit to your answer.
Concept: Both methods have security risks that must be managed carefully.
Sessions rely on secure cookies and server controls to prevent hijacking. JWTs must be signed and encrypted properly. JWTs are vulnerable if tokens are stolen because they can't be revoked easily. Sessions can be invalidated by deleting server data.
Result
You learn that security depends on implementation details, not just the method chosen.
Understanding security trade-offs prevents common vulnerabilities like token theft or session fixation.
6
ExpertChoosing Authentication for Distributed Systems
🤔Before reading on: Would you expect JWT or sessions to be better for microservices? Commit to your answer.
Concept: In distributed systems, stateless JWTs simplify authentication across services, but sessions require shared storage.
Microservices often use JWTs because tokens carry identity info and don't require central session storage. However, revoking JWTs is hard, so short token lifetimes or refresh tokens are used. Sessions need a shared database or cache to share session info, adding complexity.
Result
You understand why JWTs are popular in modern cloud apps but also their limitations.
Knowing how architecture affects authentication choice helps design scalable, secure systems.
Under the Hood
Sessions work by storing user data in server memory or a database keyed by a session ID. The client holds only the session ID cookie. On each request, the server looks up the session ID to retrieve user info. JWTs encode user info and metadata in a JSON object, base64-encoded and signed with a secret or key. The server verifies the signature to trust the token without storing any session data.
Why designed this way?
Sessions were the original method because HTTP is stateless and servers needed a way to remember users. JWTs were designed later to enable stateless authentication, especially for APIs and distributed systems, reducing server load and simplifying scaling. The tradeoff is complexity in token management and security.
┌───────────────┐          ┌───────────────┐
│   Client      │          │   Server      │
├───────────────┤          ├───────────────┤
│ Holds cookie  │          │ Stores session│
│ with session  │          │ data keyed by │
│ ID           │          │ session ID    │
└──────┬────────┘          └──────┬────────┘
       │                           │
       │ Request with cookie       │
       │──────────────────────────>│
       │                           │
       │ Server looks up session   │
       │ data and authenticates    │
       │                           │
       │ Response                  │
       │<──────────────────────────│


JWT flow:

┌───────────────┐          ┌───────────────┐
│   Client      │          │   Server      │
├───────────────┤          ├───────────────┤
│ Holds JWT     │          │ Signs and     │
│ token        │          │ verifies JWT  │
└──────┬────────┘          └──────┬────────┘
       │                           │
       │ Request with JWT          │
       │──────────────────────────>│
       │                           │
       │ Server verifies signature │
       │ and reads user info       │
       │                           │
       │ Response                  │
       │<──────────────────────────│
Myth Busters - 4 Common Misconceptions
Quick: Do you think JWT tokens can be easily revoked like sessions? Commit to yes or no.
Common Belief:JWT tokens can be revoked anytime just like sessions by deleting them on the server.
Tap to reveal reality
Reality:JWT tokens are stateless and stored on the client, so they cannot be revoked by the server until they expire or a revocation list is implemented.
Why it matters:Assuming JWTs can be revoked easily leads to security holes where stolen tokens remain valid longer than intended.
Quick: Do you think sessions always require server memory? Commit to yes or no.
Common Belief:Sessions always need server memory to store user data.
Tap to reveal reality
Reality:Sessions can be stored in external stores like databases or caches, not just in server memory, allowing better scalability.
Why it matters:Believing sessions must be in memory limits design options and scalability strategies.
Quick: Do you think JWTs are always more secure than sessions? Commit to yes or no.
Common Belief:JWTs are inherently more secure because they are signed and self-contained.
Tap to reveal reality
Reality:JWTs can be less secure if tokens are stolen because they can't be revoked easily; sessions allow immediate invalidation.
Why it matters:Overestimating JWT security can cause developers to neglect token protection and revocation strategies.
Quick: Do you think session cookies are sent automatically with every request? Commit to yes or no.
Common Belief:Session cookies are always sent automatically with every request to the server.
Tap to reveal reality
Reality:Cookies are sent only to matching domains and paths and can be controlled by flags like HttpOnly and Secure to limit exposure.
Why it matters:Misunderstanding cookie behavior can lead to security risks like cross-site attacks.
Expert Zone
1
JWT tokens often include expiration and issued-at claims to limit token lifetime and reduce risk from stolen tokens.
2
Session stores can be centralized using Redis or databases to support load-balanced servers, but this adds latency and complexity.
3
Using refresh tokens with JWTs allows short-lived access tokens and controlled re-authentication, balancing security and usability.
When NOT to use
Avoid JWTs when you need immediate token revocation or very sensitive data that must not be stored client-side. Use sessions instead when you want centralized control and easy logout. Avoid sessions in highly distributed or serverless environments where statelessness is critical.
Production Patterns
Many modern APIs use JWTs for stateless authentication combined with refresh tokens. Traditional web apps often use sessions with secure cookies. Hybrid approaches exist, like storing JWTs in HttpOnly cookies to combine benefits. Large systems use centralized session stores or token introspection endpoints for better control.
Connections
OAuth 2.0
Builds-on
Understanding JWT and sessions helps grasp OAuth 2.0 flows, which often use JWTs as access tokens to authorize users across services.
Distributed Systems
Same pattern
JWT's stateless design aligns with distributed system principles, enabling scalable authentication without centralized state.
Physical Access Control
Similar pattern
Like JWTs and sessions, physical access uses tokens (badges) or centralized checks (reception desk) to verify identity, showing how digital authentication mirrors real-world security.
Common Pitfalls
#1Storing sensitive user data directly in JWT payload.
Wrong approach:JWT payload: {"userId":123, "password":"secret"}
Correct approach:JWT payload: {"userId":123, "roles":["user"]} // no sensitive info
Root cause:Misunderstanding that JWT payload is base64 encoded but not encrypted, so anyone can read it.
#2Not setting HttpOnly and Secure flags on session cookies.
Wrong approach:Set-Cookie: sessionId=abc123; Path=/
Correct approach:Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
Root cause:Lack of awareness about cookie security flags exposing cookies to JavaScript or insecure connections.
#3Using long-lived JWTs without refresh tokens.
Wrong approach:JWT expires in 30 days, no refresh token used.
Correct approach:JWT expires in 15 minutes, refresh token used to get new JWT.
Root cause:Not understanding token expiration and the need for short-lived tokens to reduce risk.
Key Takeaways
JWT and session-based authentication are two ways to remember users after login, differing mainly in where user data is stored.
Sessions store user info on the server and use cookies to track users, while JWTs store user info inside signed tokens sent with each request.
Choosing between JWT and sessions depends on factors like scalability, security needs, and system architecture.
JWTs enable stateless, scalable authentication but require careful token management and security practices.
Sessions offer centralized control and easy revocation but need server resources and shared storage in distributed setups.

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