HTTP treats each request independently. To stay logged in, a site creates a session and gives the browser an identifier, usually in a cookie.
The cookie exchange
After login the server sends:
Set-Cookie: session=8f3a9c1e7b; Path=/; Secure; HttpOnly; SameSite=LaxThe browser sends it back on later requests:
Cookie: session=8f3a9c1e7bThe value shown is far too short for real use. A session ID must be long and random. Anyone who has it can act as that user, so treat it like a temporary password.
Attributes that protect
Secure: sent only over HTTPS.HttpOnly: page JavaScript cannot read it, which limits theft by injected script. It does not stop that script from making requests.SameSite: controls whether the cookie goes with cross-site requests.Strictsends it only with same-site requests,Laxalso allows top-level navigations such as following a link, andNonesends it cross-site but requiresSecure.Max-AgeorExpires: how long the browser keeps it. Without them it is a session cookie.
Browser defaults for SameSite differ, so set it explicitly.
Inspect with curl
curl -c jar.txt -d 'user=demo&pass=demo' https://app.example.com/login
curl -b jar.txt https://app.example.com/account-c saves received cookies to a file and -b sends them. The address and fields are placeholders. Delete the file afterwards, because it holds a working session.
Server side rules
Issue a new session ID at login, so an ID planted beforehand becomes useless. This attack is called session fixation. Expire idle sessions, and on logout destroy the session on the server. Removing only the browser's cookie leaves a copied ID valid.
Cookies are sent automatically, which allows cross-site request forgery (CSRF): another site causes the browser to send a request. Use anti-CSRF tokens for state-changing requests, with SameSite as an added layer.
Do not store trusted data such as role=admin in a plain cookie. Users can edit their cookies.
Try it
Open your browser's developer tools on a site you manage and look at its cookies. Note which have Secure, HttpOnly and SameSite. For related command line practice, use the networking and SSH lab.
Check your understanding
Sessions and Cookies
All 3 sections · no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.