Choosing between JWT and session-based authentication helps decide how your app keeps users logged in safely and easily.
0
0
JWT vs session-based decision in Spring Boot
Introduction
When you want a simple way to keep users logged in on one server.
When your app needs to work across many servers or services without sharing session data.
When you want to avoid storing user login info on the server.
When you want to control user login time and permissions easily.
When you want to keep your app fast and scalable.
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
This shows how a JWT token is created and sent with requests.
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>
This shows how a session is created and tracked with cookies.
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; } }
OutputSuccess
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.