Menu

Showing posts with label JSON Web Token. Show all posts
Showing posts with label JSON Web Token. Show all posts

15 Jun 2026

⚖️ JWT vs Session vs Cookies Explained - Part 5

JWT vs Session vs Cookies Explained
  • Welcome to Part 5 of the Authentication & Identity Security series.
  • This article explains the difference between JWT, Sessions and Cookies.
  • Designed for Middleware, DevOps, Cloud, API, and Application Support Engineers.
  • Includes enterprise examples using WebSphere, JBoss, Tomcat, Docker, Azure Entra ID, APIs, and Load Balancers.


Introduction

In previous parts, we learned about sessions, cookies, JSESSIONID, stateful applications, stateless applications, and JWT-based authentication.

Now it is important to clearly understand the difference between Cookies, Sessions and JWT. Many engineers confuse these terms and use them interchangeably, but they are different concepts.

Simple Understanding:
A cookie is stored in the browser. A session is stored on the server. A JWT is a signed token usually used for stateless authentication.

A cookie is a small piece of data stored in the user's browser. The server sends a cookie to the browser, and the browser sends it back with future requests.

Cookies are commonly used to store identifiers, preferences, tracking values, and session IDs.

Example Cookie

Set-Cookie: JSESSIONID=ABC123XYZ789; Path=/app; Secure; HttpOnly

Browser Sends Cookie Back

GET /app/dashboard HTTP/1.1
Host: www.company.com
Cookie: JSESSIONID=ABC123XYZ789
Important:
A cookie is only a storage mechanism in the browser. It is not the same as a session.

What is a Session?

A session is server-side storage used to maintain user information after login.

In Java enterprise applications, the session is commonly identified using JSESSIONID.

Session Data Example

Session ID: ABC123XYZ789

Stored on Server:
- userId = pradeep
- role = admin
- loginTime = 10:30 AM
- applicationAccess = policy-portal

The browser does not usually store this full session data. The browser only stores the JSESSIONID cookie. The actual session data remains inside the application server memory or external session store.

Common Platforms

  • IBM WebSphere Application Server
  • WebSphere Liberty
  • Apache Tomcat
  • JBoss EAP
  • WildFly

What is JWT?

JWT stands for JSON Web Token. It is a signed token that contains claims about the user or application.

JWT is commonly used in APIs, microservices, mobile applications, Docker-based applications, and cloud-native systems.

JWT Example

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiJwcmFkZWVwIiwicm9sZSI6ImFkbWluIn0.
signature

JWT Payload Example

{
  "sub": "pradeep",
  "role": "admin",
  "iss": "https://login.company.com",
  "aud": "api.company.com",
  "exp": 1789459200
}
Important:
JWT payload is encoded, not encrypted by default. Do not store passwords, secrets, or sensitive data inside JWT.

Cookie, Session and JWT Flow

Session + Cookie Flow

User Login
   │
Application Server Authenticates User
   │
Server Creates Session
   │
Server Generates JSESSIONID
   │
Browser Stores JSESSIONID Cookie
   │
Browser Sends Cookie With Every Request
   │
Server Finds Session Using JSESSIONID

JWT Flow

User Login
   │
Authentication Server Validates User
   │
JWT Generated
   │
Client Stores JWT
   │
Client Sends JWT With API Request
   │
API Validates JWT Signature and Expiry
   │
Access Granted

JWT vs Session vs Cookies Comparison

Feature Cookie Session JWT
Basic Meaning Browser storage mechanism Server-side user state Signed authentication token
Stored In Browser Application Server / External Store Client side
Common Example JSESSIONID cookie User session in JVM heap Bearer token
Stateful / Stateless Storage only Stateful Stateless
Server Memory Required No Yes, unless externalized No session memory required
Scaling Easy Requires sticky session or replication Easier horizontal scaling
Best For Session ID, preferences Traditional web applications APIs, mobile apps, microservices
Security Risk Cookie theft Session hijacking Token theft

Enterprise Middleware Example

Traditional WebSphere / JBoss / Tomcat Application

Browser
   │
JSESSIONID Cookie
   │
IBM HTTP Server / NGINX
   │
WebSphere / JBoss / Tomcat
   │
Session Stored in JVM Memory

This architecture is common in enterprise web applications. The application server stores session data and the browser stores only the JSESSIONID.

Common Requirements

  • Session timeout configuration
  • Sticky session at load balancer
  • Session replication in cluster
  • Secure and HttpOnly cookie flags
  • Logout session invalidation

Docker and Cloud Perspective

Docker does not automatically make an application stateless. If the application running inside the container stores sessions in JVM memory, it is still stateful.

Stateful Docker Application

Browser
   │
JSESSIONID Cookie
   │
Docker Container
   │
Tomcat / JBoss / WebSphere Liberty
   │
Session Stored in Container JVM Memory

If the container restarts or is replaced, in-memory sessions may be lost.

Better Cloud-Native Options

  • Use JWT-based stateless authentication
  • Use Redis as external session store
  • Use database-backed session persistence
  • Use short-lived tokens with refresh tokens
  • Use API Gateway for centralized token validation

Azure Entra ID Perspective

Azure Entra ID commonly issues tokens for modern enterprise applications and APIs.

User
 │
Application
 │
Azure Entra ID Login
 │
Access Token / ID Token
 │
Application or API Access

In this model, Azure Entra ID handles authentication and issues tokens. Applications validate the token before granting access.

Enterprise Use Case:
Azure Entra ID + OAuth2/OIDC + JWT is commonly used for SSO, API authentication, Azure applications, and cloud-native platforms.

Which One Should You Use?

Application Type Recommended Approach
Traditional WebSphere / JBoss / Tomcat web app Session + Cookie
REST API JWT / OAuth2 Access Token
Docker-based application JWT or Redis-backed session
Single Page Application OIDC with secure token handling
Enterprise SSO Azure Entra ID / SAML / OIDC
Legacy Java application Session-based authentication

Common Misconceptions

Misconception 1: Cookie and Session are Same

This is incorrect. A cookie is stored in the browser. A session is stored on the server.

Misconception 2: JWT Always Replaces Session

JWT is useful for APIs and stateless architectures, but traditional web applications may still use sessions effectively.

Misconception 3: JWT is Always More Secure

JWT security depends on implementation. Poor token storage, long expiry, missing validation, or weak signing keys can create serious risks.

Misconception 4: Docker Makes Applications Stateless

Docker only packages and runs applications. If the application stores sessions in memory, it remains stateful.


Security Best Practices

Cookie Best Practices

  • Use Secure flag for HTTPS-only transmission.
  • Use HttpOnly flag to reduce JavaScript access.
  • Use SameSite attribute to reduce CSRF risk.
  • Set proper cookie path and domain.

Session Best Practices

  • Configure proper session timeout.
  • Invalidate session after logout.
  • Regenerate session ID after login.
  • Use session replication or external session store for HA.
  • Avoid storing unnecessary large objects in session.

JWT Best Practices

  • Use HTTPS for all token communication.
  • Keep access tokens short-lived.
  • Validate signature, expiry, issuer, and audience.
  • Never store passwords or secrets in JWT payload.
  • Use refresh tokens carefully.
  • Rotate signing keys periodically.

Common Production Issues

Issue Possible Cause
User logged out randomly Session timeout, server restart, or sticky session issue
Session works on one node but fails on another No session replication or affinity
JWT gives 401 Unauthorized Expired token, invalid signature, wrong audience or issuer
Cookie not sent to server Wrong domain, path, Secure flag, or SameSite setting
High JVM memory usage Too many sessions or large session objects
Login loop Cookie, SSO, reverse proxy, or token validation issue

Key Takeaways

  • A cookie is browser-side storage.
  • A session stores user data on the server.
  • JSESSIONID is commonly stored inside a cookie.
  • JWT is a signed token used for stateless authentication.
  • Sessions are common in WebSphere, JBoss, and Tomcat applications.
  • JWT is common in APIs, Docker applications, microservices, and cloud-native systems.
  • Cookies, sessions, and JWT can all be secure or insecure depending on implementation.

What’s Next?

Next Article:
Part 6 – API Authentication & API Gateway Security

In the next article, we will understand API authentication methods such as API keys, Basic Authentication, JWT, OAuth2, and how API Gateways secure backend services.


Series: Authentication & Identity Security for Middleware, DevOps & Cloud Engineers
Author: Pradeep V
Blog: MiddlewareBox.com


🎫 JWT & Token-Based Authentication Explained - Part 4

JWT & Token-Based Authentication Explained
  • Welcome to Part 4 of the Authentication & Identity Security series.
  • This article explains JWT, access tokens, refresh tokens, and bearer tokens.
  • Designed for Middleware, DevOps, Cloud, API, and Application Support Engineers.
  • Includes enterprise examples using APIs, Docker, Azure Entra ID, API Gateway, and modern authentication flows.


Introduction

In Part 3, we learned the difference between stateful and stateless applications. Traditional enterprise applications commonly use sessions and JSESSIONID, while modern applications and APIs commonly use tokens.

One of the most popular token formats used in modern authentication is JWT.

JWT Full Form:
JWT stands for JSON Web Token.

What is JWT?

JWT, or JSON Web Token, is a compact and signed token format used to securely exchange information between a client and a server.

A JWT can carry identity and authorization information such as:

  • User ID
  • Email address
  • User role
  • Issuer
  • Audience
  • Token expiry time

JWT is commonly used in APIs, microservices, cloud applications, mobile applications, and Single Sign-On systems.


Why JWT is Used

JWT is widely used because it supports stateless authentication. The application does not need to store the user session in server memory.

  • Useful for REST APIs
  • Works well with Docker-based applications
  • Supports microservices architecture
  • Easy to validate at API Gateway level
  • Used by OAuth2 and OpenID Connect flows
  • Used by identity providers such as Azure Entra ID
Cloud View:
JWT helps applications scale horizontally because any backend server can validate the token without depending on server-side session memory.

JWT Structure

A JWT contains three parts separated by dots.

Header.Payload.Signature

Example JWT format:

xxxxx.yyyyy.zzzzz

1. Header

The header contains token type and signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

The payload contains claims. Claims are information about the user or token.

{
  "sub": "pradeep",
  "role": "admin",
  "iss": "https://login.company.com",
  "aud": "api.company.com",
  "exp": 1789459200
}

Common JWT Claims

Claim Meaning
subSubject or User ID
issIssuer of the token
audAudience or target application
expToken expiry time
iatIssued at time
roleUser role or permission

3. Signature

The signature is used to verify that the token has not been modified.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)
Important:
JWT payload is encoded, not encrypted by default. Do not store passwords, secrets, or sensitive personal data inside JWT payload.

How JWT Works

User
 │
 ▼
Login Request
 │
 ▼
Authentication Server
 │
 ▼
Credentials Validated
 │
 ▼
JWT Generated
 │
 ▼
JWT Returned To Client
 │
 ▼
Client Sends JWT With API Requests
 │
 ▼
API Validates JWT
 │
 ▼
Access Granted

Step 1: User Login

POST /login
username=pradeep
password=********

Step 2: JWT Returned

{
  "access_token": "eyJhbGciOiJIUzI1NiIs..."
}

Step 3: API Request With JWT

GET /api/customer
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

The API validates the token signature, expiry, issuer, audience, and claims before allowing access.


Is JWT Generated Every Time?

No. JWT is not generated for every API request.

A JWT is usually generated once during successful login or authentication. The same token is reused for multiple API requests until it expires.

Login
 │
JWT Generated Once
 │
Same JWT Sent With Every API Request
 │
Token Expires
 │
New Token Required

When is a New JWT Generated?

  • When the user logs in again
  • When the access token expires and a refresh token is used
  • When the authentication server rotates or renews tokens
  • When the user signs out and signs in again
Important:
The client sends the same JWT with every request using the Authorization header until the token expires.

Access Token, Refresh Token & Bearer Token

Token Type Purpose Typical Lifetime
Access Token Used to access APIs and protected resources Short-lived
Refresh Token Used to get a new access token Longer-lived
Bearer Token Token sent in Authorization header Depends on token expiry

Bearer Token Example

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Bearer means whoever has the token can use it. That is why token storage and transport security are very important.


Enterprise Middleware Example

Traditional Session-Based Application

Browser
   │
JSESSIONID Cookie
   │
IBM HTTP Server
   │
WebSphere / JBoss / Tomcat
   │
Session Stored in JVM Memory

This is commonly used in traditional enterprise web applications.

Modern JWT-Based API

Client Application
   │
Authorization: Bearer JWT
   │
API Gateway
   │
Backend API / Microservice
   │
Token Validated

This is commonly used in APIs, microservices, Docker deployments, and cloud-native applications.


Azure Entra ID Example

Azure Entra ID can act as an identity provider and issue tokens after successful authentication.

User
 │
 ▼
Application
 │
 ▼
Azure Entra ID Login
 │
 ▼
MFA / Conditional Access
 │
 ▼
Access Token Issued
 │
 ▼
Application Calls API

The API validates the token issued by Azure Entra ID before allowing access to protected resources.

Enterprise Use Case:
Azure Entra ID tokens are commonly used for Microsoft 365, Azure Portal, enterprise applications, APIs, and Single Sign-On integrations.

JWT Security Best Practices

  • Always use HTTPS to protect tokens in transit.
  • Keep access tokens short-lived.
  • Use refresh tokens carefully and store them securely.
  • Validate token signature on every request.
  • Validate issuer and audience claims.
  • Never store passwords or secrets inside JWT payload.
  • Use secure storage for tokens in browser or mobile applications.
  • Rotate signing keys periodically.
  • Use API Gateway or identity middleware for centralized validation.

Session vs JWT

Point Session JWT
ArchitectureStatefulStateless
User DataStored on serverStored as token claims
IdentifierJSESSIONIDBearer Token
ScalingNeeds sticky session or replicationEasier horizontal scaling
Common UseTraditional web appsAPIs and microservices
Example PlatformWebSphere, JBoss, TomcatAPI Gateway, Docker, Cloud APIs

Common JWT Issues

Issue Possible Cause
401 UnauthorizedToken expired or invalid
Invalid signatureWrong signing key or modified token
Audience validation failedToken issued for different API
Issuer validation failedWrong identity provider configured
Token too largeToo many claims added
Token theft riskInsecure storage or missing HTTPS

Key Takeaways

  • JWT stands for JSON Web Token.
  • JWT contains Header, Payload, and Signature.
  • JWT is commonly used for stateless authentication.
  • A JWT is usually generated during login and reused until expiry.
  • Access tokens are used to access APIs.
  • Refresh tokens are used to get new access tokens.
  • Bearer tokens are sent in the Authorization header.
  • JWT is widely used in APIs, Docker applications, cloud platforms, and microservices.

What’s Next?

Next Article:
Part 5 – JWT vs Session vs Cookies

In the next article, we will compare JWT, sessions, and cookies in detail and understand when to use each approach in enterprise applications.


Series: Authentication & Identity Security for Middleware, DevOps & Cloud Engineers
Author: Pradeep V
Blog: MiddlewareBox.com