Skip to main content
Q drop
Log in
Authentication & Security

Session management

Overview

Session management is a mechanism that makes up for the "stateless" nature of HTTP and keeps a user's logged-in state across requests. In HTTP, each request is independent by design and carries no context from before or after. In session management, when authentication succeeds, the server issues a unique session ID and stores it in a cookie in the browser. On later requests, the server verifies the session ID contained in the cookie and handles the request as coming from a logged-in user.

Generating and storing session IDs

Session IDs are generated with a cryptographically secure random number generator. Things like UUID v4 or a 256-bit random byte string are used. Predictable session IDs (sequential numbers, timestamp-based values, and so on) become targets of session hijacking attacks, so avoid using them.

On the server side, the user information tied to a session ID is stored in a database or an in-memory store. When using a NoSQL database like DynamoDB, an efficient design is to make the session ID the partition key and set a TTL (expiration time) so that expired sessions are deleted automatically.

Cookie security attributes

Session cookies need several security attributes set. The HttpOnly attribute blocks JavaScript from accessing the cookie, reducing the risk of the session ID being stolen through an XSS attack. The Secure attribute restricts the cookie to being sent only over HTTPS. The SameSite attribute mitigates CSRF attacks.

If you forget to set even one of these attributes, the attack surface for session hijacking grows. In particular, if HttpOnly is missing, a script may be able to read the session ID when an XSS vulnerability is exploited. Aim to turn on all the security attributes by default and not turn them off unless there's a clear reason.

Comparison with JWT

An alternative to session management is JWT (JSON Web Token). JWT doesn't store session information on the server and instead includes user information in the token itself. Since the server only needs to verify the token's signature, there's no need to query a database.

However, JWT has a structural weakness: tokens that have already been issued can't be revoked immediately. When a user changes their password or unauthorized access is detected, forcing existing tokens to expire requires something like a blacklist, which means keeping state on the server side to that extent. With session management, deleting the session ID from the database lets the server invalidate that session.

Was this article helpful?

Related terms

Related articles

Want to create your own question box?

Sign up with just an email address. No password required.

Start for free