Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 80 ยท Authentication and Access Control

Sessions, Cookies and JWTs

Learn how session IDs and cookie flags protect logins, how JWTs are built and verified, and how alg=none and key-confusion attacks work, with Python demos.

HTTP has no memory. Each request arrives on its own, so after a user logs in, the server needs a way to recognize them on the next request without asking for the password again. That proof of "I already logged in" is a session credential: a random session ID in a cookie, or a signed token such as a JWT. Whoever holds it is the user as far as the server can tell, which makes it as valuable as the password itself.

This lesson covers both approaches. You will see how server-side sessions work, which cookie flags matter, how a JWT is assembled and verified, and the classic JWT mistakes (alg: none, key confusion, forgotten expiry checks). You will need the ideas from HMAC and Message Authentication; the authentication that precedes a session is covered in Password Storage Done Right and Multi-Factor Authentication and Passkeys.

Server-side sessions

In the classic design the cookie holds nothing but a long random session ID. The data (user ID, role, login time) stays on the server in memory, a database or a cache such as Redis. The browser sends the cookie with each request and the server looks it up.

sequenceDiagram
    participant B as Browser
    participant S as Server
    participant T as Session store
    B->>S: POST /login (valid credentials)
    S->>T: create session, new random ID
    S-->>B: Set-Cookie: sid=ID; HttpOnly; Secure; SameSite=Lax
    B->>S: GET /account (Cookie: sid=ID)
    S->>T: look up ID
    T-->>S: user 42, created 10:02
    S-->>B: the account page
    B->>S: POST /logout
    S->>T: delete ID

The ID is only a key. Deleting the server-side record logs the user out immediately.

The rules for a good session ID:

  • Unguessable. At least 128 bits from a cryptographically secure generator (secrets.token_urlsafe(32) gives 256 bits). Never use counters, timestamps or random.
  • Meaningless. Do not encode the user name or role in it.
  • Regenerated on login (and on privilege change). If the ID stays the same before and after login, an attacker who planted a known ID in the victim's browser (session fixation) is logged in too.
  • Expiring. Use an idle timeout (for example 20 minutes for sensitive apps) and an absolute timeout (for example 12 hours), enforced on the server.
  • Destroyed on logout on the server, not just by deleting the cookie in the browser.
Python A tiny session store with fixation defense and timeouts

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 input()), it gets the next line from this box.

The server sets a cookie with a Set-Cookie header. Attributes tell the browser how to protect it:

Attribute Effect
HttpOnly JavaScript cannot read the cookie (document.cookie), so an XSS bug cannot steal it directly.
Secure Sent only over HTTPS, never over plain HTTP.
SameSite=Lax / Strict / None Controls sending on cross-site requests. Lax (the browser default now) blocks most cross-site POSTs; Strict blocks all; None requires Secure. See CSRF, SameSite and CORS.
Max-Age / Expires Lifetime. Omit both for a session cookie that disappears when the browser closes.
Path / Domain Scope. Omitting Domain keeps the cookie on the exact host; setting it exposes it to all subdomains.
__Host- name prefix The browser only accepts the cookie if it is Secure, has Path=/ and no Domain, which blocks several cookie-injection tricks.

A sound default for a session cookie is __Host-sid=<id>; Path=/; Secure; HttpOnly; SameSite=Lax.

Python Auditing Set-Cookie headers

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 input()), it gets the next line from this box.

JSON Web Tokens

A JWT (RFC 7519) is a compact, URL-safe token with three Base64URL parts separated by dots: header.payload.signature.

  • The header names the signing algorithm (alg) and sometimes a key ID (kid): {"alg":"HS256","typ":"JWT"}.
  • The payload holds claims: sub (subject, the user), iss (issuer), aud (audience, who the token is for), exp (expiry), nbf (not before), iat (issued at), plus custom claims such as roles.
  • The signature protects header.payload. With HS256 it is HMAC-SHA256(secret, "header.payload"). With RS256 or ES256 it is a public-key signature, so many services can verify tokens while only the issuer can create them.

The payload is only encoded, not encrypted. Anyone can read it, so never put passwords or private data in a standard JWT. The signature merely proves nobody changed it.

The demo builds an HS256 token from scratch and verifies it against the well-known example secret and payload that appear in many JWT references, so you can confirm the signature is correct.

Python Building and verifying an HS256 JWT

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 input()), it gets the next line from this box.

Pitfall 1: trusting the algorithm in the header

The header is part of the token, so the attacker controls it. The JWT specification includes an algorithm named none (an unsigned token). A library or hand-written verifier that reads alg from the header and obeys it can be tricked: the attacker sets "alg":"none", removes the signature, edits the claims, and the server accepts the token.

The fix is that the server decides which algorithm(s) are acceptable and passes them explicitly to the verification function. It never lets the token choose.

Pitfall 2: key confusion (RS256 versus HS256)

Suppose a service signs tokens with RS256: a private key signs, the public key verifies, and the public key is, by design, public. If the verifier picks the algorithm from the header and uses "the configured key" for whatever algorithm is named, an attacker can set "alg":"HS256" and sign the token with HMAC using the public key bytes as the HMAC secret. The server then "verifies" the HMAC with the same public key and accepts the forgery.

Real RSA is not available in this sandbox, so the next demo shows only the logic of the bug and its fix: the vulnerable verifier trusts the header; the safe one pins the algorithm and never lets a public key act as an HMAC secret.

Python alg=none and key confusion, and the fix

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 input()), it gets the next line from this box.

Pitfall 3: skipping claim validation

A valid signature says only "the issuer produced this token". You must also check that it is meant for you and still valid:

  • exp: reject expired tokens. Use short lifetimes (5-15 minutes) for access tokens.
  • nbf and iat: reject tokens used before they are valid, allowing a small clock leeway (for example 30-60 seconds).
  • iss: reject tokens from an unexpected issuer.
  • aud: reject tokens issued for a different service, otherwise a token for service A can be replayed against service B.
Python Validating JWT claims

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 input()), it gets the next line from this box.

Sessions or JWTs?

Neither is automatically better. Server-side sessions are simple and revocable on the spot: delete the record and the user is out. A JWT is stateless, so any server can verify it without a lookup, which suits APIs and microservices, but it cannot be revoked before it expires unless you add a deny-list or very short lifetimes plus a refresh token (a long-lived, revocable credential that fetches new access tokens). For a traditional website that talks to its own backend, a normal session cookie is usually the better and safer default. If you do use JWTs in a browser, keep them in HttpOnly cookies instead of localStorage, where any XSS bug can read them (Cross-Site Scripting and Output Encoding).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a new session ID be issued when a user logs in?

    If the pre-login ID stayed valid, an attacker who set it in the victim's browser would share the authenticated session. Regenerating at login invalidates that ID.
  2. 2. What does the HttpOnly cookie attribute do?

    HttpOnly hides the cookie from document.cookie, so XSS cannot read it directly. Secure and SameSite are separate attributes with different jobs.
  3. 3. Which part of a standard signed JWT is encrypted?

    A normal JWT is signed, not encrypted. Anyone holding it can read the claims, so keep secrets out of them.
  4. 4. How do you defend against alg=none and key-confusion attacks?

    The header is attacker-controlled. The verifier must pin the accepted algorithm and use the key that belongs to it.
  5. 5. A JWT has a valid signature and has not expired, but its aud is another service. What should happen?

    Checking aud stops a token meant for one service from being replayed against another. A valid signature alone is not enough.

Summary

  • A session credential is as sensitive as a password: make session IDs long, random, regenerated at login, expiring and destroyed on logout.
  • Set cookies with Secure, HttpOnly, a suitable SameSite, the narrowest scope, and the __Host- prefix where possible.
  • A JWT is header.payload.signature; it is signed (integrity) but not encrypted (not secret).
  • The server must choose the algorithm and key. Never trust alg from the token, which prevents alg=none and RS256/HS256 confusion.
  • Always validate exp, nbf, iss and aud, use short lifetimes, and plan for revocation.
  • For a typical website, server-side sessions in HttpOnly cookies are the simplest safe choice.

Next: OAuth 2.0, OpenID Connect and SSO, where one service lets users sign in with another.