Skip to content
Visual explainer 2h 30m to learn 4 steps

HTTP, cookies & sessions

Read HTTP requests and responses and explain how sessions and cookies work.

By Invicly Tech, , in Cyber Security Fundamentals. About 10 minutes to read.

Topic 23 of 49

In short

HTTP is a request and response protocol with methods and status codes. Because it is stateless, sites use cookies and sessions to remember a logged-in user. Understanding this is the basis for both attacking and defending web apps.

Explained simply

Every time you open a web page, your browser sends a request to a server and gets a response back. The request says what you want (a method like GET or POST, and a path like /account). The response says how it went with a status code, such as 200 for OK or 404 for not found, and carries the page.

Both requests and responses have headers: small name and value lines with extra information. Headers say which browser you use, what type of content is coming back, and, very importantly for security, they carry cookies.

HTTP is stateless: each request stands alone, and the server does not remember the last one. To keep you logged in, the server gives your browser a cookie with a random session ID. The browser sends it back with every request, and the server looks up who you are.

That session cookie is as good as your password while it is valid. Anyone who steals it can act as you. Much of web security is about protecting it: sending it only over HTTPS, hiding it from JavaScript and expiring it at the right time.

Press Play on a diagram to walk through it one step at a time.

SequenceA logged-in request
Browser
Server
  1. 1POST /login (credentials)
    Browser to Server: POST /login (credentials)
  2. 2Set-Cookie: session=...
    Server to Browser: Set-Cookie: session=...
  3. 3GET /account (sends cookie)
    Browser to Server: GET /account (sends cookie)
  4. 4200 OK, account page
    Server to Browser: 200 OK, account page
LayersAnatomy of one HTTP request
  1. 1
    Request line

    POST /api/orders HTTP/1.1

  2. 2
    Host header

    Which site on this server

  3. 3
    Other headers

    Cookie, Content-Type, User-Agent

  4. 4
    Blank line

    End of headers

  5. 5
    Body

    Form or JSON data, if any

In depth

Methods and status codes a defender should know

GET reads data and should never change anything on the server. POST creates or triggers actions. PUT replaces a resource, PATCH changes part of it, and DELETE removes it. HEAD is a GET without a body, and OPTIONS asks which methods are allowed; browsers send it as a CORS preflight before some cross-site requests.

GET, HEAD, PUT and DELETE are idempotent: repeating them has the same effect as doing them once. A state change behind a GET link is a classic bug, because links can be triggered by image tags, prefetching or crawlers.

Status codes come in families: 2xx success, 3xx redirect, 4xx client error and 5xx server error. In logs, patterns matter. A burst of 401s means failed logins. Many 403s from one user suggests probing for other people's data. Lots of 404s on paths like /.env or /wp-admin is a scanner. A rise in 500s after odd input can mean someone found a bug.

  • 401 not authenticated; 403 not allowed
  • 429 too many requests: your rate limit is working
  • 302 to a login page after a request often means the session expired

Cookie attributes that protect a session

A server sets a cookie with the Set-Cookie response header, and attributes control how the browser treats it. Secure means the cookie is only sent over HTTPS. HttpOnly hides it from JavaScript, so an XSS bug cannot simply read document.cookie. SameSite controls whether it is sent on requests that come from other sites: Strict never sends it cross-site, Lax sends it only on top-level navigations like clicking a link, and None always sends it but requires Secure. Chrome and other browsers treat a cookie with no SameSite as Lax, which blocks many CSRF (cross-site request forgery) attacks.

Scope matters too. A Domain attribute shares the cookie with all subdomains, so a weak subdomain can read or overwrite it. Leave Domain out to keep it on one host. The __Host- name prefix enforces this: the browser only accepts it with Secure, Path=/ and no Domain.

Max-Age or Expires make a cookie persistent; without them it is a session cookie that lasts until the browser closes.

MapParts of a well-protected session cookie
Set-Cookie: __Host-sid=...
  • Secure
    • HTTPS only
  • HttpOnly
    • Not readable by JavaScript
  • SameSite=Lax
    • Not sent on cross-site POSTs
    • Blocks most CSRF
  • Path=/, no Domain
    • One host only
    • Required by __Host- prefix
  • Short lifetime
    • Idle and absolute timeouts

Secure session management

A session ID must be impossible to guess: generated by a secure random source, with at least 64 bits of entropy (128 is common). It should carry no meaning, such as a user ID or a timestamp.

Issue a new session ID at login and whenever privileges change. If the ID stays the same from before login to after, an attacker who planted a known ID in the victim's browser gets a logged-in session; this is called session fixation.

Set two timeouts: an idle timeout (for example 15 to 30 minutes for sensitive apps) and an absolute timeout (for example 8 to 12 hours) after which the user must log in again. On logout, destroy the session on the server, not only in the browser. For high-risk actions, such as changing an email address or a password, ask for re-authentication.

Server-side sessions are easy to revoke. Self-contained tokens like JWTs are harder to revoke before they expire, so keep their lifetime short.

  • New session ID at login (stops session fixation)
  • Destroy the session server-side on logout
  • Re-authenticate before sensitive changes

Inspecting traffic in browser dev tools and curl

Open dev tools with F12 and go to the Network tab, then reload the page. Each row is one request. Click one to see the request and response headers, the cookies sent and set, the timing and the response body. Tick Preserve log to keep entries across redirects, which is how you watch a login flow. The Application tab (Storage in Firefox) lists every cookie with its flags, plus localStorage, where tokens should not be kept.

Right-click a request and choose Copy as cURL to replay it from a terminal. curl -v shows the full exchange, including the TLS handshake and headers; curl -I fetches only the headers. This is how defenders check what a server really sends, without the browser's caching or extensions getting in the way.

Be careful: a copied request includes your live session cookie. Do not paste it into tickets or chat.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Read request methods and status codes~40m
  2. 2
    Explain cookies and their flags~40m
  3. 3
    Explain session management~40m
  4. 4
    Inspect traffic in browser dev tools~40m

Key points

  • HTTP methods include GET, POST, PUT and DELETE.
  • Status codes group into 2xx, 3xx, 4xx and 5xx.
  • HTTP is stateless; cookies carry the session.
  • Cookie flags like HttpOnly and Secure protect sessions.

Key terms

Tap a card to flip it. 0/4 known

Examples

Reading a request and response with curl

Step 1: run curl -v to see both sides of the exchange. Lines starting with > are what curl sent, lines with < are what came back. Step 2: read the status line, here a redirect. Step 3: read the headers: Location says where to go next, and Set-Cookie shows the flags on the cookie. Step 4: note what is missing. This example cookie has no HttpOnly and no SameSite, which a defender would flag.

bash
curl -sv -o /dev/null https://shop.example.com/login 2>&1 | grep -E '^[<>]'
# > GET /login HTTP/2
# > host: shop.example.com
# > user-agent: curl/8.5.0
# < HTTP/2 302
# < location: /login/form
# < set-cookie: sid=9f2c...; Path=/; Secure
#   missing: HttpOnly, SameSite

Fixing a weak session cookie

An audit finds the session cookie readable by JavaScript and shared across all subdomains. Step 1: rename it with the __Host- prefix so browsers enforce Secure, Path=/ and no Domain. Step 2: add HttpOnly and SameSite=Lax. Step 3: regenerate the ID at login. Step 4: check in dev tools, Application tab, that the flags show as ticked. The Python example uses Flask to set the cookie correctly.

python
import secrets
from flask import Flask, make_response

app = Flask(__name__)

@app.post("/login")
def login():
    # ... check the password first ...
    sid = secrets.token_urlsafe(32)          # 256 random bits, new on every login
    resp = make_response("ok")
    resp.set_cookie("__Host-sid", sid, secure=True, httponly=True,
                    samesite="Lax", path="/", max_age=8 * 3600)
    return resp

Quick reference

  • GET must not change data; use POST, PUT, PATCH or DELETE for changes
  • 2xx success, 3xx redirect, 4xx client error, 5xx server error
  • Session cookie: Secure; HttpOnly; SameSite=Lax; Path=/; no Domain
  • __Host- cookie prefix forces Secure, Path=/ and no Domain
  • SameSite=None only works together with Secure
  • Issue a new session ID at login to prevent session fixation
  • curl -v shows sent (>) and received (<) headers; curl -I fetches headers only
  • Dev tools Network tab + Preserve log lets you follow a whole login flow

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which cookie attribute stops JavaScript on the page from reading the cookie?

Question 2

2A cookie is set with SameSite=Lax. When is it sent on a request started by another website?

Question 3

3Why should an app issue a new session ID right after login?

Question 4

4Your logs show thousands of 404 responses for /.env, /.git/config and /wp-login.php from one IP. What is it most likely?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Open dev tools on a site where you are logged in. Find the session cookie and write down its flags (Secure, HttpOnly, SameSite, Domain, expiry).

  2. Exercise 2medium

    Use curl to log in to a test app (for example a local lab app), save the cookies to a file, then make an authenticated request with them.

  3. Exercise 3hard

    From an nginx or Apache access log in combined format, count responses by status code family and list the top 5 IPs producing 401 or 403 responses.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a cookie and a session?
A cookie is a small value stored in the browser and sent with requests. A session is the data the server keeps about a logged-in user; the cookie usually holds only a random ID pointing to it.
Are JWTs better than session cookies?
Not by default. Server-side sessions are simpler and easy to revoke. JWTs help when many services must check identity without a shared session store, but they need short lifetimes and careful validation.
Does HTTPS hide which pages I visit?
It encrypts the path, headers and body, so a network observer cannot see them. They can still see the server's IP address and usually the host name.

Go deeper

ShareXLinkedInWhatsApp