Cookie, Session, Token, JWT, OAuth2: Which One Fits Your Project?
This article demystifies the differences between Cookie, Session, Token, JWT, and OAuth2, explains their underlying mechanisms, shows practical Spring code examples, compares their security properties and suitable scenarios, and provides clear guidance on choosing the right authentication strategy for modern web applications.
Introduction
Many developers confuse the concepts of Token, Session, Cookie, JWT, and OAuth2. This article clarifies these concepts, explains when to use each, and provides practical code examples.
1. Restaurant Analogy
To help understanding, a restaurant dining model is used as a metaphor for the authentication mechanisms.
2. Cookie: HTTP Identity Card
2.1 What is a Cookie?
A Cookie is a small piece of text data stored on the browser, sent by the server via the Set-Cookie response header and returned by the browser in subsequent requests using the Cookie header.
2.2 Cookie Practical Code
// Server sets Cookie
@PostMapping("/login")
public ResponseEntity login(@RequestBody User user, HttpServletResponse response) {
if (authService.authenticate(user)) {
Cookie cookie = new Cookie("session_id", generateSessionId());
cookie.setMaxAge(3600); // 1 hour
cookie.setHttpOnly(true); // prevent XSS
cookie.setSecure(true); // HTTPS only
cookie.setPath("/");
response.addCookie(cookie);
return ResponseEntity.ok().build();
}
return ResponseEntity.status(401).build();
}
// Read Cookie
@GetMapping("/profile")
public ResponseEntity getProfile(@CookieValue("session_id") String sessionId) {
User user = sessionService.getUserBySession(sessionId);
return ResponseEntity.ok(user);
}2.3 Important Cookie Attributes
HttpOnly : prevents JavaScript access; set to true.
Secure : transmitted only over HTTPS; set to true in production.
SameSite : controls cross‑site sending; recommend Strict or Lax.
Max-Age : cookie lifetime; set according to security needs.
3. Session: Server‑Side User Profile
3.1 What is a Session?
A Session stores user state information on the server. The server creates a unique Session ID and sends it to the browser via a Cookie; subsequent requests include this ID, allowing the server to identify the user.
3.2 Session Practical Code
// Typical Session data structure
public class UserSession {
private String sessionId;
private String userId;
private String username;
private Date loginTime;
private Date lastAccessTime;
private Map<String, Object> attributes; // custom data
}
// Login using Spring Session
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, HttpSession session) {
User user = userService.authenticate(username, password);
if (user != null) {
session.setAttribute("currentUser", user);
session.setAttribute("loginTime", new Date());
return "redirect:/dashboard";
}
return "login?error=true";
}
@GetMapping("/dashboard")
public String dashboard(HttpSession session) {
User user = (User) session.getAttribute("currentUser");
if (user == null) {
return "redirect:/login";
}
return "dashboard";
}3.3 Session Storage Options
1. In‑memory (default)
# application.yml
server:
servlet:
session:
timeout: 1800 # 30 minutes2. Redis distributed storage
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
@Bean
public LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory();
}
}4. Token: Decentralized Identity Credential
4.1 What is a Token?
A Token is a self‑contained credential; the server does not need to store session state because all required information is embedded in the token itself.
4.2 Token Practical Code
// Generate Token
public String generateToken(User user) {
long currentTime = System.currentTimeMillis();
return JWT.create()
.withIssuer("myapp")
.withSubject(user.getId())
.withClaim("username", user.getUsername())
.withClaim("role", user.getRole())
.withIssuedAt(new Date(currentTime))
.withExpiresAt(new Date(currentTime + 3600000)) // 1 hour
.sign(Algorithm.HMAC256(secret));
}
// Validate Token
public boolean validateToken(String token) {
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
.withIssuer("myapp")
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (JWTVerificationException e) {
return false;
}
}5. JWT: Modern Token Standard
5.1 What is JWT?
JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information as a JSON object, which can be verified and trusted because it is digitally signed.
5.2 JWT Structure
header.payload.signature5.3 JWT Practical Code
// Create JWT
public String createJWT(User user) {
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setSubject(user.getId())
.setIssuer("myapp")
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
.claim("username", user.getUsername())
.claim("role", user.getRole())
.signWith(SignatureAlgorithm.HS256, secret.getBytes())
.compact();
}
// Parse JWT
public Claims parseJWT(String jwt) {
return Jwts.parser()
.setSigningKey(secret.getBytes())
.parseClaimsJws(jwt)
.getBody();
}5.4 JWT Best Practices
Store JWT in HttpOnly Cookie or in‑memory, not in localStorage.
Use short‑lived access tokens with a refresh token mechanism.
// Token pair
public class TokenPair {
private String accessToken; // ~1 hour
private String refreshToken; // ~7 days
}
@PostMapping("/refresh")
public ResponseEntity refresh(@RequestBody RefreshRequest request) {
String refreshToken = request.getRefreshToken();
if (validateRefreshToken(refreshToken)) {
String userId = extractUserId(refreshToken);
String newAccessToken = generateAccessToken(userId);
return ResponseEntity.ok(new TokenPair(newAccessToken, refreshToken));
}
return ResponseEntity.status(401).build();
}6. OAuth 2.0: Authorization Framework
6.1 What is OAuth 2.0?
OAuth 2.0 is an authorization framework that allows third‑party applications to access protected resources on behalf of a user after obtaining the user's consent.
6.2 OAuth 2.0 Authorization Code Flow
6.3 OAuth 2.0 Practical Code
// Spring Security OAuth2 configuration
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp")
.secret(passwordEncoder.encode("123456"))
.authorizedGrantTypes("authorization_code", "refresh_token")
.scopes("read", "write")
.redirectUris("http://localhost:8080/callback");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter());
}
}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.antMatchers("/api/private/**").authenticated()
.antMatchers("/api/admin/**").hasRole("ADMIN");
}
}7. Comparison of the Five Concepts
A concise table (omitted here) compares Cookie, Session, Token, JWT, and OAuth2 in terms of essence, storage location, primary use, and key characteristics, as well as their security considerations such as XSS, CSRF, token leakage, and data tampering.
Conclusion
Cookie is the carrier for HTTP state; Session stores server‑side state; Token is a credential that can be placed in Cookie, Header, or URL; JWT is a standardized, self‑contained token; OAuth2 is a framework that defines a complete third‑party authorization flow. Choose the solution that best fits your application scenario rather than looking for a universally "best" option.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
