| |

Web Security 09 🛡️ Session, Cookie & JWT Architecture — Securing HttpOnly cookies, refresh token rotation, and avoiding JWT pitfalls

⏱️ Estimated read: 10 min | |

State management is a fundamental challenge in web development because HTTP is inherently stateless. Every request is an isolated event, unaware of those that came before it. To build functional applications, developers must implement mechanisms to “remember” a user’s identity across multiple requests. This is typically achieved through either stateful sessions, where the server stores session data and the client holds a session ID, or stateless tokens (JWTs), where the session state is cryptographically signed and stored entirely on the client.

The security of these architectures depends heavily on how the identifiers are stored and transported. If an attacker can steal a session ID or a JWT, they can impersonate the user perfectly. This chapter dissects the security configurations required to protect these identifiers, focusing on the critical role of cookie attributes, the implementation of refresh token rotation for long-lived sessions, and the architectural pitfalls that often lead to JWT vulnerabilities.

We will explore three main areas: the specific browser-level flags that shield cookies from script-based theft and cross-site forgery, the secure lifecycle of JSON Web Tokens including the Access/Refresh token pattern, and the common implementation errors that compromise token-based authentication.

Key point: The security of a session architecture is defined by its storage location and transport mechanism; using HttpOnly and Secure cookies is the primary defense against token theft via XSS, while refresh token rotation mitigates the impact of a leaked credential.


Why X exists

1. The statelessness problem.

HTTP does not preserve context. Without a session or token, a user would have to provide credentials for every single action, from clicking a link to submitting a form. Session architecture exists to provide a persistent identity that “bridges” these disconnected requests.

2. The horizontal scaling problem.

In traditional stateful sessions, user data is stored in the server’s memory. If an application scales to multiple servers, a user’s request might land on a server that doesn’t “know” them. This led to the adoption of centralized stores (like Redis) or stateless JWTs, where the server doesn’t need to store anything locally to verify a user.

3. The XSS theft problem.

If an authentication token is stored in localStorage or sessionStorage, it is accessible to any JavaScript running on the page. In the event of a Cross-Site Scripting (XSS) vulnerability, an attacker can simply read the token and send it to their own server. HttpOnly cookies exist specifically to prevent JavaScript from accessing these sensitive identifiers.

4. The CSRF forgery problem.

While cookies are safer from XSS, they are vulnerable to Cross-Site Request Forgery (CSRF) because browsers automatically attach them to cross-site requests. Security architectures must include specific cookie attributes like SameSite to prevent the browser from sending session identifiers in unintended, malicious contexts.

5. The token revocation problem.

Stateless JWTs are valid until they expire. If a user logs out or their account is compromised, there is no built-in way to “kill” the token because the server doesn’t track it. This architectural reality necessitates the use of short-lived access tokens and longer-lived, rotatable refresh tokens.


a. Securing the Transport: Cookie Attributes

Cookies remain the most secure way to store session identifiers or JWTs because they support browser-enforced security flags. When a server sends a Set-Cookie header, it should include specific attributes to restrict how that cookie is used and accessed.

// Example: Setting a secure session cookie in Express
res.cookie('session_id', 'xyz-123-abc', {
  httpOnly: true, // Prevents JavaScript access (XSS defense)
  secure: true,   // Only sent over HTTPS (Man-in-the-Middle defense)
  sameSite: 'lax',// Restricts cross-site usage (CSRF defense)
  path: '/',      // Scope of the cookie
  maxAge: 3600000 // 1 hour expiration
});

The HttpOnly flag is non-negotiable for authentication tokens. It ensures that even if an attacker manages to inject a script into your page, document.cookie will not reveal the session ID. The Secure flag ensures the cookie is never sent over an unencrypted connection, protecting it from network sniffing. Finally, SameSite=Lax or Strict ensures the cookie is only sent when the user is actually interacting with your site, neutralizing most CSRF attacks.


b. JWT Architecture: Access and Refresh Tokens

In a modern JWT-based system, we use two different tokens to balance security and user experience. The Access Token is short-lived (e.g., 15 minutes) and used to authorize API requests. Because it is checked frequently, it should be stateless. The Refresh Token is long-lived (e.g., 7 days) and used only to obtain a new access token.

// The Access Token (Short-lived)
const accessToken = jwt.sign(
  { userId: 123 }, 
  process.env.ACCESS_TOKEN_SECRET, 
  { expiresIn: '15m' }
);

// The Refresh Token (Long-lived, stored in a database)
const refreshToken = jwt.sign(
  { userId: 123 }, 
  process.env.REFRESH_TOKEN_SECRET, 
  { expiresIn: '7d' }
);

To maximize security, implement Refresh Token Rotation. Every time a refresh token is used to get a new access token, the old refresh token is invalidated, and a new one is issued. If an attacker steals a refresh token and uses it, the legitimate user’s next attempt to refresh will fail because their token was already rotated. The server, seeing a reused token, can then revoke the entire session family, effectively logging out the attacker.


c. Avoiding Common JWT Pitfalls

JWTs are powerful but notoriously easy to implement incorrectly. The most famous vulnerability is the alg: none attack, where an attacker changes the header to specify no signature is required. Modern libraries protect against this, but developers must still manually verify the algorithm during the decoding process.

// WRONG: Decoding without explicit algorithm check
const payload = jwt.verify(token, secret); 

// RIGHT: Enforcing the expected algorithm
const payload = jwt.verify(token, secret, {
  algorithms: ['HS256'] // Explicitly ignore 'none' or other unexpected types
});

Another pitfall is storing sensitive data in the JWT payload. JWTs are signed, not encrypted. Anyone who can see the token (including the user) can decode it and read the data inside using tools like jwt.io. Never store passwords, PII, or internal system secrets in the payload. Finally, always verify the exp (expiration) and iss (issuer) claims to ensure the token is still valid and was generated by your own auth server.


Complete Example Session

// ============================================
// PART 1: TOKEN ISSUANCE (LOGIN)
// ============================================
async function login(req, res) {
  const user = await authenticate(req.body);
  const accessToken = generateAccessToken(user);
  const refreshToken = generateRefreshToken(user);

  // Store Refresh Token in DB for rotation logic
  await db.refreshTokens.create({ token: refreshToken, userId: user.id });

  // Send Refresh Token in a Secure, HttpOnly cookie
  res.cookie('jid', refreshToken, { httpOnly: true, secure: true, sameSite: 'lax' });

  // Send Access Token in JSON response (to be kept in memory)
  res.json({ accessToken });
}

// ============================================
// PART 2: THE REFRESH LOGIC (ROTATION)
// ============================================
app.post('/refresh_token', async (req, res) => {
  const token = req.cookies.jid;
  if (!token) return res.send({ accessToken: '' });

  // 1. Verify token signature and expiration
  let payload;
  try {
    payload = jwt.verify(token, process.env.REFRESH_SECRET);
  } catch (err) {
    return res.status(401).send({ ok: false });
  }

  // 2. Check if token exists in DB (to prevent reuse)
  const savedToken = await db.refreshTokens.find(token);
  if (!savedToken) {
    // Detect reuse! This token was already used. Potential attack.
    await db.refreshTokens.deleteForUser(payload.userId);
    return res.status(403).send({ ok: false });
  }

  // 3. Rotate the token
  await db.refreshTokens.delete(token); // Invalidate old
  const newRefreshToken = generateRefreshToken(payload.userId);
  await db.refreshTokens.save(newRefreshToken); // Save new

  res.cookie('jid', newRefreshToken, { httpOnly: true, secure: true });
  res.json({ accessToken: generateAccessToken(payload.userId) });
});

// ============================================
// PART 3: ACCESS TOKEN VALIDATION
// ============================================
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) return res.sendStatus(401);

  jwt.verify(token, process.env.ACCESS_SECRET, { algorithms: ['HS256'] }, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

This example demonstrates the Access/Refresh token pattern with database-backed rotation, ensuring that tokens are securely stored and the server can react to token misuse.


Quick Reference

Essential Cookie Flags

FlagPurposeAttack Prevented
HttpOnlyDisallows JS accessXSS token theft
SecureOnly over HTTPSNetwork sniffing
SameSite=LaxRestricts cross-siteCSRF (General)
SameSite=StrictRestricts all cross-siteCSRF (Strict)

Token Properties

PropertyAccess TokenRefresh Token
LifespanShort (5-15 mins)Long (days/weeks)
StorageMemory (JS variable)HttpOnly Cookie
PurposeAuthorizationGetting new Access Tokens
Stateful?No (usually)Yes (for rotation/revocation)

JWT Claims

ClaimMeaningSecurity Use
subSubjectUser Identifier
expExpirationPrevents indefinite usage
iatIssued AtTracks token age
issIssuerVerifies trust source

Best Practices

✅ Do This:

// Store Refresh Tokens in HttpOnly cookies               // ✅
// Use short-lived Access Tokens (5-15 mins)              // ✅
// Implement Refresh Token Rotation                       // ✅
// Explicitly define 'algorithms' in jwt.verify           // ✅
// Use a strong, random secret from environment variables // ✅
// Set the Secure flag on all cookies in production        // ✅

❌ Don’t Do This:

// Don't store JWTs in LocalStorage                       // ❌
// Don't put sensitive PII (emails/PII) in JWT payload    // ❌
// Don't use 'none' as an algorithm                       // ❌
// Don't use a constant string as a secret                // ❌
// Don't forget to verify the 'exp' claim                 // ❌
// Don't ignore token reuse in the database               // ❌

Common Pitfalls

PitfallWhy It HappensFix
LocalStorage JWTEasy to implement in SPAsUse HttpOnly cookies
alg: none attackParser trust in headerSet algorithms: ['HS256']
No revocationStateless JWTs stay validUse Refresh Token Rotation
Payload leakageThinking JWT is encryptedStore only ID/Claims
Missing Secure flagLocal dev environmentUse secure: process.env.NODE_ENV === 'prod'
CSRF via CookieAutomatic browser behaviorSet SameSite=Lax

Real-World Examples

1. HttpOnly Cookie Setting

res.cookie('token', val, { httpOnly: true });

2. SameSite Lax (Standard)

res.cookie('token', val, { sameSite: 'lax' });

3. Explicit Alg Verification

jwt.verify(token, secret, { algorithms: ['HS256'] });

4. Access Token in Memory

let currentAccessToken = null; // Stays in JS memory, not storage

5. Deleting Refresh Token

await db.tokens.delete({ token: req.cookies.jid });

6. Refresh Token Rotation

if (used) { revokeAll(); throw Error(); }

7. Secure flag check

const isProd = process.env.NODE_ENV === 'production';

8. Short Expiration

jwt.sign(payload, secret, { expiresIn: '15m' });

9. JWT Payload (Safe)

{ "uid": 5, "role": "admin" } // No secrets here

10. Header Authorization

headers: { 'Authorization': `Bearer ${token}` }

Visual

Stateful Session vs Stateless JWT

┌──────────────────────────────────────────────────────────┐
│  SESSION-BASED (Stateful)                                │
│  Client: [Cookie: SID=123] ──────► Server: [Look up 123] │
│                                      │                   │
│  TOKEN-BASED (Stateless)             └─► DB: {User Data} │
│  Client: [Cookie: JWT=xyz...] ─────► Server: [Verify Sig]│
│                                      │                   │
│                                      └─► Payload is Data │
└──────────────────────────────────────────────────────────┘

Refresh Token Rotation Logic

┌──────────────────────────────────────────────────────────┐
│  1. User sends Refresh Token A                           │
│  2. Server verifies A, Checks DB                         │
│  3. Server deletes A from DB                             │
│  4. Server creates Refresh Token B, saves to DB          │
│  5. Server sends B (Cookie) + new Access Token (JSON)    │
│                                                          │
│  * If Attacker tries to use A again ──► REUSE DETECTED   │
│  * Server revokes B and locks account                    │
└──────────────────────────────────────────────────────────┘

Cookie Security Shield

┌──────────────────────────────────────────────────────────┐
│  THE BROWSER COOKIE JAR                                  │
│  ┌────────────────────────────────────────────────────┐  │
│  │ Cookie: auth_token                                 │  │
│  ├────────────────────────────────────────────────────┤  │
│  │ HttpOnly ──► Blocks XSS (document.cookie)          │  │
│  │ Secure   ──► Blocks MITM (Non-HTTPS)               │  │
│  │ SameSite ──► Blocks CSRF (Cross-Site Requests)      │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Preferred StorageHttpOnly Cookie
Best XSS DefenseHttpOnly flag
Best CSRF DefenseSameSite flag
Access Token Life5 – 15 Minutes
Refresh Token Life1 – 14 Days
JWT VerificationSignature + Exp + Algorithm
Revocation StrategyRefresh Token Rotation

Key takeaways:

  • Cookies over LocalStorage. Storing tokens in localStorage makes them trivially easy to steal via XSS. Use HttpOnly cookies to keep tokens away from malicious scripts.
  • Use the Access/Refresh pattern. Never issue a single JWT that lasts for hours. Keep the access token extremely short-lived and use a rotatable refresh token to manage session length.
  • Implement Refresh Token Rotation. Tracking refresh tokens in a database allows the server to detect if a token is reused, which is a strong indicator of theft.
  • JWTs are not private. Any information put into a JWT payload can be read by the client. Only store identifiers and non-sensitive claims like user roles.
  • Enforce algorithms. Prevent alg: none attacks by explicitly defining the expected cryptographic algorithm (like HS256 or RS256) when verifying tokens.
  • Cookies need flags. Without Secure and SameSite, cookies are vulnerable to network sniffing and cross-site forgery. Always configure these flags in production.

Remember: A secure session architecture is a multi-layered defense. You use cookies to prevent theft, short-lived tokens to limit the window of opportunity for an attacker, and rotation to detect and neutralize compromised credentials. No single setting is enough; you must combine storage security, transport security, and architectural logic to build a truly resilient authentication system.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!