How to Manage Session Tokens Securely
Issue opaque session tokens, store only their hash, rotate on privilege change, and revoke cleanly so a stolen token has a short life.
On this page
Introduction
A session token is a bearer credential: whoever holds it is treated as the user. That makes its generation, storage, rotation and revocation the core of session security. A token that is predictable can be guessed; one stored in plaintext in the database is exposed by a database leak; one that never rotates stays valid after a password change; one that cannot be revoked outlives the logout. This article covers issuing an opaque token, storing only a hash, rotating at the right moments, and the cookie flags that keep the token out of reach of scripts and cross-site requests.
Opaque Tokens Versus Self-Contained Tokens
A self-contained token such as a JWT carries its claims and is verified by signature, so the server need not look it up. That is convenient for stateless services but makes revocation hard: a JWT is valid until it expires unless you maintain a denylist, which reintroduces the state you were avoiding. An opaque session token is a random identifier that means nothing on its own and must be looked up in a store, which makes revocation and rotation trivial.
For a session that a user logs out of or that should end when a password changes, the opaque token is the better choice. Use a self-contained token for short-lived, machine-to-machine access where revocation matters less, and prefer opacity for user sessions where it does.
Generating and Storing the Token
The token must come from a cryptographically secure random source, long enough that guessing is infeasible: at least 128 bits, encoded in a URL-safe form. Store only a hash of the token, so a leak of the store does not yield usable tokens. On each request, hash the presented token and look up the hash, which is a constant-time-safe comparison by way of the lookup.
const crypto = require('node:crypto');
// Issue: random token, store only a SHA-256 hash.
function issueToken() {
const token = crypto.randomBytes(32).toString('base64url'); // 256 bits
const hash = crypto.createHash('sha256').update(token).digest('hex');
return { token, hash }; // give the token to the client, store the hash
}
// Verify: hash the presented token and look up the hash.
async function resolveSession(db, presentedToken) {
const hash = crypto.createHash('sha256').update(presentedToken).digest('hex');
const row = await db.query(
'SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = $1',
[hash],
);
const s = row.rows[0];
if (!s || s.revoked_at || s.expires_at < new Date()) return null;
return s;
}
Rotation at the Right Moments
Rotate the session token when privilege changes: on login, and on any elevation such as a password change or a role change. Rotation on login prevents session fixation, where an attacker sets a token before the user logs in and then uses the now-authenticated session. The old token must be invalidated at the same moment the new one is issued, so a stolen pre-login token is useless after login.
Do not rotate on every request, which would break concurrent tabs and add a write per request. Rotate on the events that matter: login, logout, privilege elevation, and periodic re-authentication for highly sensitive operations. Each rotation is a write, so keep them to the moments where they add security.
Expiry and Revocation
A session should expire: absolutely, after a maximum lifetime, and idly, after a period of inactivity. Absolute expiry bounds how long a stolen token is useful; idle expiry frees the store and limits the window for a token left on a shared machine. The store must support immediate revocation, so a logout or a compromise can end a session now rather than waiting for expiry.
Keep a way to revoke all sessions for a user, for the case where the account is compromised and every token must be invalidated at once. Store the sessions per user so a single update revokes them all, and check the revoked flag on every request. A token that cannot be revoked is a login that cannot be logged out.
CREATE TABLE sessions (
token_hash text PRIMARY KEY, -- the token itself is never stored
user_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, -- absolute expiry
last_seen_at timestamptz NOT NULL DEFAULT now(), -- for idle expiry
revoked_at timestamptz
);
-- Logout: revoke this one session immediately.
UPDATE sessions SET revoked_at = now() WHERE token_hash = $1;
-- Password change / compromise: revoke every session for the user.
UPDATE sessions SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL;
-- Idle expiry: sessions untouched for longer than the idle window are dead.
DELETE FROM sessions
WHERE last_seen_at < now() - interval '30 minutes' OR expires_at < now();
Cookie Flags and Storage
The session token should travel in a cookie with HttpOnly, Secure and SameSite set. HttpOnly keeps it out of reach of page scripts, so an XSS cannot read it; Secure keeps it off plaintext connections; SameSite limits cross-site sending, which mitigates CSRF. Give the cookie a path and a short max-age matching the session lifetime, and avoid storing the token in localStorage, which any script can read.
The cookie name can carry a prefix, such as the host prefix that scopes the cookie to the exact host and prevents a subdomain from setting it. Set the expiry in the cookie to match the session so the browser stops sending a token the server would reject, and clear the cookie on logout.
Common Pitfalls
Storing the token in plaintext is the most damaging: a database leak then hands the attacker live sessions. Not rotating on login enables session fixation. Making the token predictable, such as a sequence or a hash of the user id, enables guessing. Failing to revoke on logout leaves a logout that does not log out. And putting the token in a place scripts can read turns any XSS into account takeover.
Each of these has a fix that is cheap at design time and expensive after an incident. Store the hash, use a secure random source, rotate on privilege change, revoke on logout and password change, and put the token in an HttpOnly Secure cookie. None of them is novel; the failure is doing only some of them.
Conclusion
A session token is a bearer credential, so treat it as one. Generate it from a secure random source, store only its hash, rotate it on login and privilege change to prevent fixation, expire it absolutely and idly, and revoke it immediately on logout or compromise, including all sessions for a user. Put it in an HttpOnly, Secure, SameSite cookie and never in localStorage. Then a stolen token has a short life and a leak of the store yields nothing usable.
Sources: OWASP: Session Management Cheat Sheet, MDN: Set-Cookie, OWASP: Session fixation.
FAQ
- Why store only the hash of a session token?
- So a leak of the session store does not hand an attacker usable tokens. The server hashes the presented token and looks up the hash, and the plaintext token exists only on the client. This is the same reasoning as password hashing.
- Why rotate the session token on login?
- To prevent session fixation: an attacker who sets a token before the user logs in would otherwise hold the now-authenticated session. Rotating on login issues a fresh token and invalidates the pre-login one, so the fixated token is useless.
Report a problem with this articleOpens a pre-filled issue on GitHub.