Sessions, Tokens and JWT Pitfalls

Topics Covered

Sessions and Session Identifiers

Authentication versus session management

Server side sessions

Session identifiers

Session fixation

Stateless tokens

Bearer semantics

Lifetimes and timeouts

Logout and invalidation

Device and session visibility

Choosing a design

Where sessions are stolen

Concurrent session limits

Session storage security

After a user proves who they are, the application has to remember that proof for every later request. HTTP is stateless, so each request must carry something that identifies the authenticated session, either a reference to state on the server or a self contained token. How this credential is created, stored, transmitted, checked and ended decides whether an attacker who steals one request, one cookie or one log line can become the user. This lesson covers server side sessions, cookies, bearer tokens, JSON Web Tokens and the long list of ways they go wrong.

Authentication versus session management

Authentication is the moment a user proves their identity, with a password, a passkey, a one time code or a single sign on flow. Session management is everything afterwards: issuing a credential that represents the authenticated user, checking it on each request, refreshing it and ending it. Strong authentication is wasted if session management is weak, because attackers rarely bother to break a login when they can steal or forge the session that follows it. Many of the largest account takeover incidents involve stolen session cookies or tokens rather than passwords.

Server side sessions

The traditional design stores session state on the server. After login, the server creates a session record containing the user identifier, creation time, last activity time and any attributes, stores it in a database or cache and sends the browser a random session identifier in a cookie. On each request the server looks up the identifier and loads the session. The identifier itself carries no meaning, so it cannot be forged or tampered with, and the server can end a session instantly by deleting the record. The cost is a lookup on every request and a shared store.

Session identifiers

A session identifier must be unguessable. It should be generated by a cryptographically secure random generator with at least 128 bits of entropy, encoded in a URL safe form and never derived from user data, timestamps or counters. Frameworks generate suitable identifiers by default, and the most common failures come from custom code that builds identifiers from user identifiers and times or uses general purpose random functions. An identifier that can be predicted, even partially, lets an attacker enumerate valid sessions.

With a million live sessions and a billion guesses a second, a 32 bit identifier falls in under a millisecond and a 64 bit one in about 5 hours. A 128 bit identifier would take about 10 to the 16 years.

Session fixation

Session fixation is an attack in which the attacker gets the victim to use a session identifier the attacker already knows, for example by planting it through a link or a subdomain cookie, and then waits for the victim to log in. If the application keeps the same identifier after login, the attacker now holds an authenticated session. The defence is simple: issue a new session identifier whenever the privilege level changes, especially at login, and invalidate the old one. Most frameworks offer a regenerate function for exactly this purpose.

Stateless tokens

The alternative design puts the session state into a token that the client carries, signed by the server so it cannot be modified. Each service that receives the token verifies the signature and reads the user identifier and other claims directly, without a database lookup. This suits distributed systems and APIs where many services must check identity, and it is how most modern access tokens work. The price is that the token remains valid until it expires, because there is no central record to delete, which makes logout and revocation harder.

Bearer semantics

Most session cookies and access tokens are bearer credentials: whoever presents them is treated as the user, with no further proof. That means every place a bearer credential appears is a place it can be stolen, including browser storage, logs, URLs, analytics tools, error reports, proxies and screenshots in support tickets. Handling bearer credentials safely means keeping them out of all those places. Proof of possession designs, which bind a token to a key the client holds, reduce this risk and are discussed later in the lesson.

Lifetimes and timeouts

Sessions need two timeouts. An idle timeout ends a session after a period without activity, such as 30 minutes for a banking application or several days for a social application. An absolute timeout ends a session after a maximum lifetime regardless of activity, forcing reauthentication. Without an absolute limit, a stolen session that the attacker keeps active lasts forever. Sensitive actions, such as changing an email address, adding a payment method or viewing secrets, should also require recent authentication, regardless of how long the session has been open.

Logout and invalidation

Logout must end the session on the server, not only delete the cookie in the browser. If the server keeps the session valid, anyone who copied the cookie earlier can continue using it. Applications should also offer a way to end all sessions, used when a password is changed, when a user reports a lost device and when an account is recovered. For stateless tokens, invalidation needs extra machinery, such as short lifetimes, refresh token revocation or a deny list, which the later sections cover.

Device and session visibility

Users and support teams benefit from seeing active sessions: the device, approximate location, start time and last activity for each. A user who sees an unfamiliar session can end it, and a support engineer handling a takeover report can end every session at once. Storing this metadata also gives the security team signals for detection, such as a session that suddenly moves between distant locations or appears from hosting provider address ranges. These features cost little with server side sessions and need deliberate design with stateless tokens.

Choosing a design

For a web application with its own backend, server side sessions in secure cookies are usually the simplest and safest choice, with instant revocation and no token parsing. Stateless tokens fit APIs consumed by many services, mobile apps and third party clients, especially when combined with short lifetimes and a refresh mechanism. Many systems use both: a cookie session for the web front end and short lived tokens for calls between the backend and internal services. The right design follows who presents the credential and who must verify it.

Where sessions are stolen

Real session theft rarely involves breaking cryptography. Common paths are malware on the user device that copies browser cookies, cross site scripting that reads tokens from page accessible storage, tokens leaked into logs, analytics or referrer headers, and phishing proxies that sit between the user and the real site and capture the session after the user completes multi factor authentication. Each path suggests defences covered in this lesson, from cookie flags to token binding and detection of unusual session behaviour.

Concurrent session limits

Some applications limit how many sessions one account may hold at once, or notify the user when a new session starts on an unfamiliar device. A limit of a few sessions per account makes credential sharing visible and caps the number of stolen sessions that can stay active unnoticed. Notifications give the real user a chance to react within minutes rather than discovering misuse weeks later. These controls work best when the notification includes a direct link to review and end sessions, so the user can act on it without contacting support.

Session storage security

A server side session store holds every active session, which makes it a valuable target. Store hashes of session identifiers rather than the identifiers themselves, so a leaked database dump or cache snapshot cannot be replayed. Restrict network access to the store, require authentication on the cache, encrypt connections and avoid putting sensitive data such as payment details inside session records. Expired sessions should be removed promptly, both to limit exposure and to keep the store small enough to stay fast under load.

Protect what comes after login

Treat the session credential as valuable as the password. Generate identifiers with 128 bits of randomness, regenerate them at login, set idle and absolute timeouts, require recent authentication for sensitive actions, end sessions on the server at logout and give users and support a way to see and end every session.