A Complete Guide to Cookie, Session, Token, OAuth2.0, SSO, and JWT
This article systematically explains the concepts, workflows, advantages, drawbacks, and practical code examples of Cookie, Session, Token, OAuth2.0, Single Sign‑On (SSO) and JWT, compares them, offers best‑practice recommendations, and provides interview‑style Q&A for developers.
Fundamental concepts
Cookie
Definition: Small file stored by the browser and automatically sent with each HTTP request.
Workflow: User logs in → server returns Set‑Cookie → browser stores the cookie → subsequent requests automatically include Cookie header.
✅ Auto‑sent with requests
✅ Can be shared across sub‑domains via Domain ❌ Vulnerable to XSS and CSRF attacks
❌ Size limited to ~4 KB
Security attributes example:
Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict; Max-Age=3600Code example:
// Server sets cookie
response.addCookie(new Cookie("sessionId", "abc123"));
// Browser automatically sends
GET /api/user HTTP/1.1
Cookie: sessionId=abc123Session
Definition: Server‑side storage of user data linked to a SessionId that is kept in a cookie.
Workflow: User logs in → server creates a session → returns SessionId as a cookie → later requests send the cookie → server looks up the session.
✅ Data stays on the server (more secure)
✅ Can store complex objects
❌ Consumes server memory
❌ Difficult to share in distributed environments
❌ Requires cleanup of expired sessions
Distributed session problem: A load balancer may route a subsequent request to a different server that does not have the session, causing the user to appear unauthenticated.
Typical solutions:
Session replication between servers
Centralized store (e.g., Redis)
Switch to stateless token authentication
Code example:
// Create session
HttpSession session = request.getSession();
session.setAttribute("userId", 123);
session.setMaxInactiveInterval(3600); // 1 hour
// Retrieve session later
HttpSession session = request.getSession(false);
if (session != null) {
Integer userId = (Integer) session.getAttribute("userId");
}Token
Definition: Server‑issued credential carried by the client (usually in an Authorization header) and validated on each request.
Workflow: User logs in → server generates token → returns token → client includes token in Authorization: Bearer <token> header for subsequent calls.
✅ Stateless – no server‑side storage needed
✅ Naturally fits distributed systems
✅ CORS‑friendly
✅ Works on mobile clients
❌ Cannot be revoked without a blacklist
❌ Token leakage is risky
Comparison with Session:
Storage location – Session: server, Token: client
State – Session: stateful, Token: stateless
Distributed friendliness – Session: difficult, Token: easy
Revocation – Session: immediate, Token: requires blacklist
Size – Session: small, Token: relatively large
Code example:
// Generate token
String token = generateToken(userId);
response.setHeader("Authorization", "Bearer " + token);
// Validate token
String token = request.getHeader("Authorization").replace("Bearer ", "");
if (validateToken(token)) {
// token is valid
}Advanced schemes
JWT (JSON Web Token)
Definition: Self‑contained token format that embeds user claims and a cryptographic signature.
Structure: Header.Payload.Signature Example token parts:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cHeader (JSON): {"alg":"HS256","typ":"JWT"} Payload (claims) example:
{"sub":"1234567890","name":"John Doe","iat":1516239022,"exp":1516242622}Signature: HMAC‑SHA256 of base64url‑encoded header and payload using a secret.
Pros:
✅ Self‑contained – no DB lookup required
✅ Tamper‑proof via signature
✅ Cross‑origin friendly
✅ Mobile‑friendly
Cons:
❌ Token size can be large because it carries all claims
❌ Cannot be revoked instantly
❌ Exposure leads to immediate risk
Refresh mechanism: Issue a short‑lived access token (e.g., 15 min) and a long‑lived refresh token (e.g., 7 days). When the access token expires, the client sends the refresh token to obtain a new access token.
POST /api/token/refresh
{
"refreshToken": "xxx"
}
Response:
{
"accessToken": "yyy",
"expiresIn": 900
}OAuth2.0
Definition: Authorization framework that lets users grant third‑party applications access to their resources.
Core entities: Resource Owner (user) → Authorization Server (e.g., WeChat, Google) → Client Application → Resource Server (API).
Four grant types:
Authorization Code (most common)
Implicit (deprecated)
Resource Owner Password Credentials (internal systems)
Client Credentials (service‑to‑service)
Authorization Code flow example (WeChat):
// Build authorization URL
String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + APPID +
"&redirect_uri=" + REDIRECT_URI +
"&response_type=code" +
"&scope=snsapi_userinfo";
// Exchange code for access token
String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + APPID +
"&secret=" + SECRET +
"&code=" + code +
"&grant_type=authorization_code";
// Use access token to get user info
String userUrl = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + accessToken +
"&openid=" + openId;SSO (Single Sign‑On)
Definition: Users log in once and gain access to multiple related systems without re‑authenticating.
Workflow: User accesses System A → redirected to SSO server → logs in → SSO server issues a token (or shared cookie) → user accesses System B → System B validates the token, no additional login required.
Difference from OAuth2.0:
Purpose – OAuth2.0: authorization, SSO: authentication
Typical users – OAuth2.0: different companies, SSO: same company
Scenario – OAuth2.0: third‑party login, SSO: internal enterprise systems
Example – OAuth2.0: WeChat login, SSO: corporate intranet
Implementation options:
Cookie‑based SSO – shared domain cookie
Token‑based SSO – SSO server issues token, each system validates it
SAML – enterprise‑grade standard for large organizations
Token‑based SSO code snippet:
// SSO server generates token
String ssoToken = generateSSOToken(userId);
response.addCookie(new Cookie("sso_token", ssoToken));
// System A validates token
String ssoToken = request.getCookie("sso_token");
if (validateSSOToken(ssoToken)) {
// auto login
}
// System B validates token (same logic)Practical application
Sa‑Token framework
Lightweight Java permission and authentication library.
Core features: Login authentication, RBAC, token management, gateway integration.
Maven dependency:
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.37.0</version>
</dependency>Typical API usage:
// Login
StpUtil.login(userId);
// Check login status
StpUtil.checkLogin();
// Get current user ID
Long userId = StpUtil.getLoginId();
// Logout
StpUtil.logout();
// Permission check
StpUtil.checkPermission("user:add");
// Role check
StpUtil.checkRole("admin");Best practices
Security recommendations
Enforce HTTPS to prevent man‑in‑the‑middle attacks.
Set reasonable token expiration times.
Require re‑authentication for sensitive operations.
Rotate signing keys regularly.
Use strong passwords.
Enable multi‑factor authentication.
Performance tips
Cache token validation results.
Store sessions in Redis for scalability.
Avoid frequent database lookups.
Prefer JWT to reduce server‑side storage.
Common pitfalls
Missing token refresh mechanism.
No blacklist for revocation.
Improper CORS handling.
Lack of CSRF protection.
Hard‑coded secrets in code.
Interview questions (standard answers)
Cookie vs Session: Storage – Cookie in browser, Session on server; Security – Cookie vulnerable to XSS/CSRF, Session more secure; Performance – Cookie no DB lookup, Session requires lookup; Distributed – Cookie works out‑of‑the‑box, Session needs special handling; Size – Cookie ≤4 KB, Session unlimited.
JWT pros & cons: Pros – Stateless, supports distributed systems, cross‑origin friendly, mobile‑friendly; Cons – Large size, cannot be revoked instantly, risk if leaked, requires refresh flow.
OAuth2.0 grant types: Authorization Code, Implicit (deprecated), Resource Owner Password Credentials, Client Credentials.
SSO vs OAuth2.0: SSO provides authentication within the same organization; OAuth2.0 provides authorization for third‑party access.
Choosing an authentication scheme: Simple app → Cookie + Session; Distributed system → Token + JWT; Third‑party login → OAuth2.0; Enterprise intranet → SSO; Fine‑grained permission → RBAC (Sa‑Token).
Summary of schemes
Cookie + Session – Suitable for traditional web apps; Advantages: simple, secure; Disadvantages: hard to scale horizontally.
Token – Suitable for distributed systems; Advantages: stateless, easy to scale; Disadvantages: cannot revoke easily.
JWT – Suitable for microservices; Advantages: self‑contained, tamper‑proof; Disadvantages: larger token size.
OAuth2.0 – Suitable for third‑party login; Advantages: standard, secure; Disadvantages: complex flow.
SSO – Suitable for enterprise intranet; Advantages: good user experience; Disadvantages: implementation complexity.
Reference links:
https://mp.weixin.qq.com/s/9WW67naQQTRtTCb_cHg8LA
https://mp.weixin.qq.com/s/abhYTjpshCQo4Tbyv71GYw
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.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
