Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 133 ยท Security and Cryptography

Authentication: Sessions and JWT

Build login in Node.js two ways - server-side cookie sessions and signed JWTs with node:crypto - then add refresh token rotation with reuse detection, and learn when to choose which.

Authentication answers one question: who is making this request? HTTP is stateless, so each request arrives without memory of the previous one. After a user proves their identity once (with a password, as in Passwords, scrypt and Tokens), your server must recognize that user on every later request without asking for the password again. Two designs solve this problem, and almost every login system is one of them or a mix.

  • Server-side sessions. The server keeps the state. The browser holds only a random, meaningless session id in a cookie, and the server looks it up on each request.
  • Tokens such as JWT. The server hands out a signed, self-describing token containing the user id and an expiry. Later requests carry the token, and any server holding the signing key can verify it without a lookup.

In this lesson you will build both with nothing but node:http and node:crypto, then add refresh tokens, the piece that makes short-lived tokens usable. The goal is not to replace a battle-tested library in production but to understand every moving part, so you can configure one correctly and spot mistakes.

Authentication code is security code. In production, prefer a maintained library or an identity provider, keep it updated, and have the design reviewed. Everything below follows common best practice, but your threat model and compliance needs may require more.

A session works like a coat check. When you log in, the server creates a record (the coat) in its store, and gives you a ticket number (the cookie). Whenever you come back with the ticket, the server finds your record. The ticket itself says nothing about you; it must simply be impossible to guess, so it comes from crypto.randomBytes with at least 128 bits, and we use 256 here (never Math.random(), see Random Values and IDs).

Rules for the session cookie, set with the Set-Cookie header from Headers, Cookies and Caching:

  • HttpOnly: JavaScript in the page cannot read it, so an XSS bug cannot steal it.
  • Secure: only sent over HTTPS (always on in production; our loopback demo uses plain HTTP).
  • SameSite=Lax (or Strict): the browser does not attach it to most cross-site requests, which blocks the common CSRF attacks.
  • Max-Age and Path=/: a lifetime and the scope. Also keep the lifetime on the server (expiresAt), because the client's clock is not trustworthy.

Two server-side rules are just as important. Regenerate the session id at login: if an attacker planted a known id in the victim's browser before login (session fixation), the old id must stop working. And destroy the record at logout, not only the cookie.

The example below is a complete login system over a loopback server: login with a scrypt-checked password, a protected /me route, logout, and the fixation test. The client keeps its own tiny cookie jar, because Node's fetch has none.

Node.js Server-side sessions with cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Observe the error message for a failed login: it is the same whether the username or the password was wrong, so attackers cannot discover which accounts exist. Real systems also rate-limit logins and lock or slow down repeated failures; see Web Application Security.

Sessions have one big advantage: revocation is trivial. Delete the record and the user is signed out immediately, on every device, at once. The costs are a lookup per request and shared storage once you run several server instances. With more than one process, keep sessions in Redis or a database rather than a Map (see MongoDB and Redis from Node.js).

Because browsers send cookies automatically, cookie-based sessions need CSRF protection for state-changing requests: SameSite, a CSRF token for forms, or checking the Origin header.

Most Express applications do not write the session store by hand; they use a package. Two are common, and they are different designs:

  • express-session is the server-side kind you just built. The cookie holds a signed session id, and the data lives in a store: the default MemoryStore is for development only (it leaks memory and is lost on restart); production uses a store package such as connect-redis or connect-mongo.
  • cookie-session keeps the whole session inside the cookie, signed so the client cannot change it. There is no store and no lookup, but the data is limited to about 4 KB, is visible to the user (signed, not encrypted), and cannot be revoked from the server.
JavaScript
import express from 'express';
import session from 'express-session';
import { RedisStore } from 'connect-redis';

const app = express();
app.set('trust proxy', 1);                       // needed for secure cookies behind a proxy

app.use(session({
  name: 'sid',                                   // do not keep the default name "connect.sid"
  secret: [process.env.SESSION_SECRET, process.env.OLD_SESSION_SECRET], // first signs, all verify
  store: new RedisStore({ client: redisClient }),
  resave: false,                                 // do not rewrite unchanged sessions
  saveUninitialized: false,                      // no cookie for visitors who never log in
  rolling: false,                                // true renews the expiry on every response
  cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 30 * 60 * 1000 },
}));

app.post('/login', async (req, res, next) => {
  const user = await verifyCredentials(req.body);
  if (!user) return res.status(401).json({ error: 'Invalid username or password' });
  req.session.regenerate((err) => {              // new id: prevents session fixation
    if (err) return next(err);
    req.session.userId = user.id;                // session variables are plain properties
    req.session.save(() => res.json({ ok: true }));
  });
});

app.post('/logout', (req, res) => {
  req.session.destroy(() => {                    // deletes the record in the store
    res.clearCookie('sid');
    res.sendStatus(204);
  });
});

The settings that cause the most confusion are resave and saveUninitialized. Set both to false unless you have a reason: saveUninitialized: false means anonymous visitors do not receive a cookie or a store entry (fewer sessions, and compliant with consent rules for cookies), and resave: false avoids writing back sessions that did not change. Session data is read and written as normal properties of req.session, and it is saved automatically at the end of the response. Call req.session.save() yourself only when you redirect immediately and must be sure the store finished writing.

The signature is what stops forged ids. In express-session the cookie value is s: plus the session id, a dot, and an HMAC of the id made with your secret. A client who makes up an id cannot produce the signature, so the server rejects it without any store lookup. Because the secret can be an array, you can rotate it: sign with the first entry, accept all entries, and drop the old one after a session lifetime has passed. cookie-session signs the whole payload in the same way. This example shows both mechanisms and their limits:

Node.js Signed session ids and a signed cookie session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both designs reject forged or edited cookies, but they trade differently. With express-session, revoking a user is store.destroy(id) and the cookie is tiny; with cookie-session, there is no shared storage to run, but the user can read the data, the size is capped, and a stolen cookie works until it expires. If the session holds anything secret, or you need "sign out everywhere", use the server-side store. The same trade-off, with tokens instead of cookies, is the topic of the next section.

For the Passport layer that sits on top of these sessions (strategies, serializeUser, req.user), see Passport.js: Authentication Strategies.

JSON Web Tokens

A JWT (pronounced "jot") packs claims into a string with three base64url parts separated by dots: header.payload.signature.

  • The header names the algorithm, for example {"alg":"HS256","typ":"JWT"}.
  • The payload holds claims: sub (subject, the user id), exp (expiry, seconds since 1970), iat (issued at), iss (issuer), aud (audience), and anything else you add.
  • The signature is an HMAC (or a public-key signature) over header.payload. Anyone can read the payload, because it is only encoded, not encrypted. Nobody without the key can change it undetected.

So a JWT is a tamper-proof note, not a secret. Never put passwords or private data in it.

The server verifies a token in five steps: split into three parts, check that the header's algorithm is the one you expect, recompute the signature and compare it in constant time, parse the payload, and check the claims (exp, nbf, iss, aud). Skipping any of these has caused real vulnerabilities, including the infamous alg: none bug where a library accepted unsigned tokens because the header said so. The example implements all five with node:crypto, takes the clock as a parameter so it is testable, and attacks itself.

Node.js Signing and verifying a JWT by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The tampered token changed role to admin, but the old signature no longer matches, so it is refused. This is the whole security of a JWT: only holders of the key can produce a valid signature.

HS256 or RS256?

HS256 uses one shared secret: every service that verifies tokens can also forge them. That is fine when one application issues and checks its own tokens. When many services only need to verify tokens, use an asymmetric algorithm such as RS256 (RSA) or ES256 (ECDSA): the issuer signs with a private key and everyone else verifies with the public key. Keep a kid (key id) header so you can rotate keys, and publish public keys at a JWKS endpoint. node:crypto can sign with crypto.sign(); for ES256 pass { dsaEncoding: 'ieee-p1363' } because JWT uses the raw r||s format rather than DER.

The revocation problem and the access/refresh split

A session can be deleted. A JWT cannot: until exp, any server with the key will accept it, even after the user logs out or is banned. The standard answer has two parts:

  1. Make the access token short-lived (5 to 15 minutes) and keep it in memory or an HttpOnly cookie.
  2. Add a long-lived refresh token that can be revoked, used only to obtain a new access token.
sequenceDiagram
    participant B as Browser
    participant A as API
    participant S as Token store
    B->>A: POST /login (username, password)
    A->>S: save hash of refresh token R1
    A-->>B: access token (15 min) + refresh token R1
    B->>A: GET /data with access token
    A-->>B: 200
    Note over B,A: 15 minutes later the access token expires
    B->>A: GET /data with expired token
    A-->>B: 401
    B->>A: POST /refresh with R1
    A->>S: mark R1 used, save R2
    A-->>B: new access token + refresh token R2

The browser spends short-lived access tokens on every call and trades the refresh token for a new pair only when needed.

Refresh token rotation with reuse detection

A refresh token is a high-value secret, so treat it like a password: make it opaque (random bytes, not a JWT), store only its hash on the server, and rotate it on each use. Each refresh returns a new refresh token and marks the old one as used.

Rotation gives you a powerful detector. If an already-used refresh token shows up again, then either the thief or the real user is replaying a stolen copy. You cannot tell which, so you revoke the whole family (every token descended from that login) and force a fresh login. The thief loses access; the real user logs in once more.

Node.js Refresh tokens with rotation and theft detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Storing only hashes means a leaked database does not leak usable refresh tokens. A fast hash such as SHA-256 is fine here, unlike for passwords, because the tokens have 256 bits of randomness and cannot be guessed. (See Hashing and HMAC for why.)

Where does the client keep the tokens?

  • Browser apps: the safest place for a refresh token is an HttpOnly, Secure, SameSite cookie scoped to the refresh path. Keep the access token in memory. Avoid localStorage for either, because any XSS bug can read it.
  • Mobile and native apps: use the platform's secure storage (Keychain, Keystore).
  • Server-to-server: short-lived tokens issued by an identity provider, with keys stored in a secret manager (Configuration, Secrets and Environment).

Sessions or JWT?

Cookie sessions JWT access + refresh
Server state A record per login Only refresh tokens
Instant logout / ban Yes, delete the record Only at the next refresh (or with a deny-list)
Lookup per request Yes No, just a signature check
Several services verifying users Need shared store Easy, especially with public-key signing
Browser apps on one site Excellent default More moving parts
Mobile apps and third-party APIs Awkward Natural

For a typical website with its own backend, start with sessions. They are simpler and safer by default. Choose tokens when many independent services or non-browser clients must verify identity, and then keep access tokens short and refresh tokens rotated. Whichever you choose, always use HTTPS, hash passwords with a slow function, rate-limit login, and log security events.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the session id be regenerated when a user logs in?

    If the id stayed the same, an attacker who set it earlier would share the logged-in session. A fresh id makes the planted one useless.
  2. 2. What does the signature of a JWT protect?

    The payload is only base64url-encoded, so anyone can read it. The signature only proves that nobody without the key altered it.
  3. 3. Why does the verifier compare header.alg with the algorithm it expects, instead of trusting the token?

    The header is attacker-controlled input. The server must decide which algorithms it accepts.
  4. 4. A refresh token that was already used is presented again. What should the server do?

    Rotation means each refresh token works once. A second use signals a replay, so the safest response is to revoke the family and require a new login.
  5. 5. Which is a real advantage of server-side sessions over JWTs?

    A JWT stays valid until it expires, unless you add extra state. Deleting a session record revokes it at once.

Summary

  • HTTP is stateless, so after login you need a way to recognize the user: a server-side session (random id in a cookie) or a signed token (JWT).
  • Session cookies should be HttpOnly, Secure, SameSite, random (at least 128 bits), regenerated at login and deleted at logout.
  • A JWT is header.payload.signature; the payload is readable by anyone. Verify the algorithm, the signature (in constant time), exp, nbf, iss and aud.
  • Make access tokens short-lived and pair them with opaque refresh tokens that are stored hashed and rotated on every use. Reuse of an old token means theft: revoke the family.
  • Default to sessions for a website; use tokens when several services or non-browser clients need to verify identity.

Next: Compression with zlib