Fixing Session Fixation in a Remember Me Cookie

Rotating session IDs in an e-commerce API

The scenario

Our e‑commerce API was built on a stateless REST layer that delegated authentication to a central identity service. The API accepted a short‑lived bearer token (JWT) and, for convenience, exposed a “Remember Me” feature that let users stay logged in across browser restarts. The implementation was simple: the client stored a cookie named REMEMBER_ME that contained a signed, encrypted token. When the browser sent the cookie back, the API would issue a new JWT and refresh the cookie.

The cookie was set with the following attributes:

Set-Cookie: REMEMBER_ME=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...
Domain=.example.com; Path=/; Secure; HttpOnly

No SameSite flag was present, and the cookie was not marked SameSite=Lax. The token was a JWT that carried the user ID, an expiration timestamp, and a session_id claim that was generated once per login and never changed.

When a user logged in, the identity service created a new session_id and stored it in the user’s row in the database. The API accepted the session_id from the JWT and used it to look up the user’s session state (cart, preferences, etc.). The session_id was never regenerated after the first login.

How the attack unfolded

An attacker discovered that the API accepted any REMEMBER_ME cookie that was signed with the public key of the identity service. The attacker could craft a cookie with a forged session_id that pointed to a session the attacker had created earlier. Because the API did not validate that the session_id matched the authenticated user’s record, the attacker could hijack a legitimate user’s session.

The attack vector was straightforward:

  1. Session creation – The attacker logged in as a low‑privilege user (e.g., a test account) and captured the REMEMBER_ME cookie.
  2. Session fixation – The attacker used the captured cookie to set a new cookie on the victim’s browser by exploiting a cross‑site scripting (XSS) payload or a CSRF form that set the cookie.
  3. Privilege escalation – The victim, unaware, performed actions that the attacker could now see and manipulate because the session_id was shared.

The root cause was that the session_id was static per login and the cookie was not bound to the user’s identity beyond the signed JWT. The API trusted the session_id claim without cross‑checking the user’s record, creating a classic session‑fixation vulnerability.

Why rotating session IDs matter

A rotating session ID is a session identifier that changes on every authentication event or after a configurable period. When a session ID changes, any old tokens or cookies that reference the previous ID become invalid. This mitigates:

  • Session fixation – An attacker cannot reuse a known session ID after the user logs in.
  • Cross‑site request forgery (CSRF) – Rotating IDs make it harder for an attacker to predict or replay a valid session.
  • Account takeover – If an attacker steals a cookie, it will be short‑lived and unusable after the legitimate user logs in again.

The OWASP Session Management Cheat Sheet recommends rotating session IDs on every login and after a configurable number of requests or time period. (See https://owasp.org/www-project-session-management/)

Implementing rotating session IDs in a stateless API

Below is a step‑by‑step walkthrough that shows how to refactor the existing “Remember Me” flow to use rotating session IDs while keeping the API stateless.

Instead of embedding the session ID in the JWT, generate a random, opaque token (e.g., a 256‑bit UUID) and store it in a cookie. The token is the only thing the client sends back; the server uses it to look up the session in a fast key‑value store (Redis, DynamoDB, etc.).

Set-Cookie: REMEMBER_ME=6f3c2a1b-4d8e-4c3f-9b2e-1a2b3c4d5e6f
Domain=.example.com; Path=/; Secure; HttpOnly; SameSite=Lax

The token is not a JWT; it is just a random string. The server signs the token with a server‑side secret and stores the mapping token → session_id in Redis with a TTL that matches the cookie’s expiration.

2. Issue a short‑lived JWT on each request

When the client presents the REMEMBER_ME cookie, the API:

  1. Looks up the token in Redis.
  2. Retrieves the associated session_id.
  3. Generates a new JWT that contains the user_id and the fresh session_id.
  4. Returns the JWT in the Authorization header and optionally refreshes the cookie if the TTL is close to expiring.

The JWT is still used for stateless request authentication, but the session_id inside it is now dynamic and tied to the cookie.

3. Rotate the session ID on every login

When a user logs in (POST /auth/login):

def login(username, password):
    user = db.get_user(username)
    if not user or not verify_password(password, user.hash):
        raise Unauthorized()

    # Generate a new session ID
    session_id = secrets.token_hex(32)

    # Store session data in Redis
    redis.setex(f"session:{session_id}", SESSION_TTL, json.dumps({
        "user_id": user.id,
        "created_at": time.time(),
        "last_active": time.time()
    }))

    # Generate a remember‑me token
    remember_token = secrets.token_hex(32)
    redis.setex(f"remember:{remember_token}", REMEMBER_TTL, session_id)

    # Return JWT and set cookie
    jwt = create_jwt(user.id, session_id)
    response = make_response(jsonify({"token": jwt}))
    response.set_cookie(
        "REMEMBER_ME",
        remember_token,
        max_age=REMEMBER_TTL,
        domain=".example.com",
        path="/",
        secure=True,
        httponly=True,
        samesite="Lax"
    )
    return response

Key points:

  • New session ID per login – The attacker cannot reuse an old session ID.
  • Separate remember‑me token – The token is only a pointer to the session ID; it is not itself a session identifier.
  • Redis TTLs – The session and remember tokens expire automatically, reducing the window for abuse.

4. Invalidate old sessions on logout

When a user logs out, delete both the session and the remember token:

def logout(request):
    token = request.cookies.get("REMEMBER_ME")
    if token:
        session_id = redis.get(f"remember:{token}")
        if session_id:
            redis.delete(f"session:{session_id}")
        redis.delete(f"remember:{token}")
    response = make_response(jsonify({"message": "Logged out"}))
    response.delete_cookie("REMEMBER_ME", domain=".example.com", path="/")
    return response

This ensures that a logged‑out user cannot be hijacked by an old cookie.

5. Protect against replay attacks

Because the remember‑me token is opaque, an attacker who steals it can still hijack the session. To mitigate this:

  • Bind the token to the user agent – Store the user agent string in Redis along with the session. On each request, compare the stored UA with the current request’s UA. If they differ, invalidate the session.
  • IP binding – Optionally bind the session to the client IP. This is more restrictive and may hurt usability for mobile users, so use it judiciously.

6. Monitor for abnormal session activity

Implement a simple audit log:

def log_session_activity(session_id, action, ip, ua):
    redis.rpush(f"session:{session_id}:log", json.dumps({
        "action": action,
        "timestamp": time.time(),
        "ip": ip,
        "ua": ua
    }))

If you see repeated logins from the same IP with different session IDs, trigger an alert.

Common pitfalls and how to avoid them

Pitfall Why it matters Fix
Missing SameSite flag Allows cross‑site cookie leakage via CSRF or XSS. Set SameSite=Lax or Strict depending on your UX.
Long‑lived JWTs Even if the remember‑me cookie is stolen, a long‑lived JWT can be used. Keep JWTs short‑lived (5–15 min) and rotate them on each request.
Storing session data in the JWT Increases token size and exposes sensitive data if the token is intercepted. Store only minimal claims; keep session data server‑side.
Not invalidating old tokens on logout Allows attackers to use old cookies after the user logs out. Delete both session and remember tokens on logout.
Using predictable session IDs Enables attackers to guess or brute‑force session IDs. Use cryptographically secure random tokens (secrets.token_hex).

Troubleshooting tips

  • Cookie not being set – Verify that the Secure flag is only used over HTTPS. In development, you can omit it but remember to re‑enable it in production.
  • Redis connection errors – Use a connection pool and set a reasonable timeout. Monitor Redis memory usage; session data should be lightweight.
  • JWT verification failures – Ensure the signing key is rotated regularly and that the key is stored securely (e.g., AWS KMS, HashiCorp Vault).
  • Session expiration too aggressive – Adjust SESSION_TTL and REMEMBER_TTL based on user behavior. A typical pattern is 30 min for sessions and 30 days for remember‑me tokens.
  • User agent mismatch – If legitimate users report being logged out unexpectedly, consider relaxing the UA binding or providing a fallback mechanism.

Trade‑offs

Benefit Trade‑off
Improved security Slightly more complex backend (Redis, token rotation).
Better user experience Users may see a brief “re‑auth” prompt if the remember‑me token expires.
Stateless API Requires a fast, highly available key‑value store; adds network latency for token lookup.
Auditability Logging every session activity increases storage and processing overhead.

Final checklist

  • Generate a new session ID on every login.
  • Store session data in a fast key‑value store with TTL.
  • Issue an opaque remember‑me token that points to the session ID.
  • Set cookies with Secure, HttpOnly, and SameSite=Lax.
  • Rotate JWTs on each request; keep them short‑lived.
  • Invalidate session and remember tokens on logout.
  • Bind sessions to user agent/IP if feasible.
  • Monitor session activity for anomalies.
  • Test the flow with tools like Postman, curl, and automated scripts.

By following this pattern, the “Remember Me” feature becomes a secure, user‑friendly convenience rather than a vector for session‑fixation attacks. The key is to treat the session ID as a secret that must never be reused across logins and to keep the client‑side cookie as a simple, opaque reference rather than a bearer of sensitive claims.

See also