Session vs Token Auth
TechLearningPRO Orders must choose how identity travels after login: a server-side session (opaque cookie ↔ session store) or a self-contained token (JWT bearer, no server sessi…
Introduction
TechLearningPRO Orders must choose how identity travels after login: a server-side session (opaque cookie ↔ session store) or a self-contained token (JWT bearer, no server session).
On Boot 3 / Security 6, session auth uses cookies and a shared store (often Redis); token auth uses SessionCreationPolicy.STATELESS plus an OAuth2 resource server or custom JWT filter.
Sessions revoke instantly by deleting the session id. JWTs scale horizontally but need short TTLs, refresh rotation, or a deny-list for urgent revocation.
This lesson compares the two for Orders so you pick per surface — browser admin UI vs mobile/API — without mixing insecure hybrids by accident.
Purpose of this lesson
Decide when Orders should use cookie sessions versus bearer JWT, and configure Security 6 accordingly on Boot 3 / Java 21.
Understanding the topic
Session and token auth solve the same identity problem with different state and revocation trade-offs.
- Session: server holds principal; cookie carries only a session id.
- Token (JWT): client holds claims; server verifies signature/issuer each request.
- Revocation: sessions delete in Redis; JWTs need TTL, rotation, or deny-list.
- Scale: sessions need sticky affinity or a shared store; JWT is naturally horizontal.
- Hybrid: cookie session for the Ops UI; JWT for mobile and service-to-service.
Step-by-step explanation
- List Orders clients: browser SPA, mobile app, internal services — map each to session or token.
- For APIs, set
sessionCreationPolicy(STATELESS)and enableoauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())). - For classic server-rendered admin, keep sessions and store them in Redis under a dedicated profile.
- Document revocation: logout deletes session; JWT logout rotates refresh and optionally blacklists
jti.
Informative example
Stateless JWT chain for Orders API vs session-friendly defaults.
@Configuration@EnableWebSecuritypublic class SecurityConfig {@BeanSecurityFilterChain api(HttpSecurity http) throws Exception {return http.securityMatcher("/api/**").csrf(csrf -> csrf.disable()).sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**", "/actuator/health").permitAll().anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build();}@BeanSecurityFilterChain adminUi(HttpSecurity http) throws Exception {return http.securityMatcher("/admin/**").authorizeHttpRequests(auth -> auth.anyRequest().hasRole("ADMIN")).formLogin(Customizer.withDefaults()).logout(logout -> logout.logoutSuccessUrl("/admin/login")).build();}}
Real-world use
TechLearningPRO first shipped Orders with sticky sessions behind one JVM. When the mobile team added a second region, sticky cookies broke logout and carts. Moving the public API to JWT with short access tokens and Redis-backed refresh rotation removed affinity while the internal admin UI kept cookie sessions for instant revoke.
Security implications
Auth model choice is a security control, not just a scaling preference.
- Stolen JWTs remain valid until expiry unless you track
jti. - Session fixation and CSRF matter for cookie flows — enable CSRF there.
- Secrets for signing keys live in env placeholders such as
${JWT_SIGNING_KEY}— never in source.
Best practices
- Prefer STATELESS + JWT for public Orders APIs; sessions for trusted browser admin only.
- Keep access tokens short; store refresh tokens server-side or rotate them.
- Never mix cookie session auth and CSRF-off on the same browser surface.
Common mistakes
- Putting JWT in localStorage without XSS hardening, or using long-lived access tokens with no rotation.
- Disabling CSRF on cookie-session browser flows.
- Assuming JWT logout is instant without a deny-list or short TTL.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhen prefer JWT over server sessions for an Orders API?+
Answer
2IntermediateQuestionWhy is JWT logout harder than session logout?+
Answer
3IntermediateQuestionIs CSRF still required with STATELESS JWT bearer APIs?+
Answer
Hands-on exercise
Lab. Split Security into two chains: STATELESS JWT for /api/orders/** and form login for /admin/**. Prove an API call with no bearer fails, and that admin logout clears the session store entry.
Summary
Session vs token auth is the Orders identity trade-off: shared session store and instant logout versus stateless JWT scale with careful TTL and rotation.