Why Do We Need Cookies and Sessions?
HTTP is stateless. To track logged-in users, we need a mechanism to store and transfer user identity between client and server. This is where cookies and sessions come in.
1. Cookie-Based Login (Client-Side Identity)
How It Works
- When login is successful, the server stores the user's ID in a cookie:
Cookie idCookie = new Cookie("memberId", String.valueOf(user.getId()));
response.addCookie(idCookie);
- On future requests, the client sends the cookie, and the server retrieves the user ID from it:
@CookieValue(name = "memberId", required = false) Long memberId;
Pros
- Easy to implement
- No server memory is used to track login
Cons
- Security risk: Users can modify cookies and impersonate other users
- Cookies can be stolen via XSS or intercepted if not using HTTPS
- Cannot store sensitive data
Example Attack
A user could manually change the cookie:
Cookie: memberId=2
If user ID 2 is valid, they gain access to another user’s data.
2. Session-Based Login (Server-Side Identity)
Concept
- Server generates a session ID (e.g., UUID) and stores login data on the server
- Client only receives a cookie with the session ID:
HttpSession session = request.getSession();
session.setAttribute("loginUser", user);
- Future requests automatically send the session ID via a JSESSIONID cookie, and the server fetches the user object
Built-in: HttpSession
Spring uses the built-in servlet session API:
HttpSession session = request.getSession();
session.setAttribute("loginUser", loginMember);
To read the session:
Member member = (Member) session.getAttribute("loginUser");
Or using Spring annotation:
@SessionAttribute(name = "loginUser", required = false) Member member
Logging Out
Invalidate session to logout:
HttpSession session = request.getSession(false);
if (session != null) session.invalidate();
Pros
- Sensitive data stays on the server
- Safer against cookie tampering
Cons
- Requires server memory
- If not explicitly logged out, session remains until timeout
Session Timeout Configuration
- Global (in application.properties):
server.servlet.session.timeout=1800 # seconds (30 min)
- Per session:
session.setMaxInactiveInterval(1800); // 30 minutes
✅ Session Creation & Sending Session ID to the Client
1. Create a Session on the Server
HttpSession session = request.getSession(); // or request.getSession(true)
session.setAttribute("loginMember", member); // Store user information
2. Server Internally Generates a Session ID
- A random UUID is typically generated as the session ID.
- Example: JSESSIONID=ABC1234-XYZ-5678...
3. Server → Client: Send Session ID via Set-Cookie Header
Set-Cookie: JSESSIONID=ABC1234XYZ5678; Path=/; HttpOnly
- The browser stores this cookie.
4. Client → Server: Automatically Sends the Cookie in Subsequent Requests
Cookie: JSESSIONID=ABC1234XYZ5678
- The server retrieves the user info from the session storage using the session ID.
💡 Example: getSession(true) vs getSession(false)
// Case 1: Create a new session if it does not exist
HttpSession session1 = request.getSession(true); // or simply request.getSession()
System.out.println("Session ID (create if needed): " + session1.getId());
// Case 2: Get the existing session, but do NOT create a new one
HttpSession session2 = request.getSession(false);
if (session2 != null) {
System.out.println("Existing session ID: " + session2.getId());
} else {
System.out.println("No session exists.");
}
Code Example Comparison
Cookie Login (Not Recommended for Production)
@PostMapping("/login")
public String login(HttpServletResponse response) {
Cookie cookie = new Cookie("memberId", "1");
response.addCookie(cookie);
return "redirect:/";
}
HttpSession Login (Recommended)
@PostMapping("/login")
public String login(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("loginUser", loginMember);
return "redirect:/";
}
Comparison Table
Method | Storage | Security | Use Case |
Cookie | Client-side | Vulnerable to tampering | Very simple, low-security use only |
Custom Session | Server-side (manual) | More secure, but DIY logic | Educational or legacy systems |
HttpSession | Server-side (auto) | Built-in, configurable | Recommended for modern web apps |
Best Practices
- Use HttpSession or Spring Security for secure login management
- Store minimal user data in sessions (e.g., user ID, name)
- Prevent JSESSIONID from leaking via URLs:
server.servlet.session.tracking-modes=cookie
- Avoid long session lifetimes to reduce risk if stolen
Final Note
Spring also offers Spring Security, a powerful library that handles authentication, sessions, login/logout, and more — all with best security practices baked in. Consider using it for production systems.
'JAVA Spring' 카테고리의 다른 글
API Exception Handling (0) | 2025.04.11 |
---|---|
Error Handling & Error Pages (0) | 2025.04.11 |
Servlet Filter vs Spring Interceptor (0) | 2025.04.11 |
Bean Validation (0) | 2025.04.08 |
Spring MVC Validation (0) | 2025.04.07 |