Identity and access Cookies 4 min read
How do cookies work?
Yesterday a shop set a cookie in your browser. Today you visit the shop again. Does your browser ask you before handing it back?
-
Set once, handed back automatically
A server sets a cookie with a header like
Set-Cookie: theme=dark; Path=/; Max-Age=2592000; Secure. The browser stores it.From then on, the browser includes it on every matching request to that site, without asking, until it expires. That automatic behaviour is what makes cookies so useful, and so worth protecting.
Set once by the server, returned by the browser on every matching request. In short The server sets it once; the browser does the rest.
-
Which requests carry it
Each part of the header decides where the cookie goes. Without a
Domainattribute, only the exact host that set it gets it back; another site never does.Path=/accountlimits it to pages under/account.Securemeans HTTPS only.Max-Agesays how many seconds it lives. Without it, orExpires, it’s a session cookie, gone when the browser closes.In short Site, path, HTTPS and expiry must all match, or it stays behind.
-
The user holds the cookie
A site stores
role=adminin a cookie and shows admin pages to anyone whose cookie says so. But cookies live in the user’s browser, and anyone can open the developer tools and change them.Store a random ID in the cookie instead, and keep facts like the role on the server, where the user can’t reach them.
The server sets a cookie saying role equals user. The person edits it in their browser to role equals admin and sends it back. The server trusts the cookie and opens the admin pages.
The server set it. The user changed it. In short Never trust what’s in a cookie. Use it as a key to look things up.
What a cookie doesn’t do
A cookie isn’t private from the user, and isn’t protected from being changed. It’s a note the browser carries, nothing more.
And because browsers include it automatically, other sites can trigger requests that carry it. That’s what HttpOnly, SameSite and CSRF defences are for.
Keep this
The browser keeps the cookie and includes it automatically, whenever site, path and settings match.
The user controls their own cookies. Never trust what’s in one; use it as a key to look things up on the server.- Set
- The server sends Set-Cookie.
- Kept
- The browser stores it per site.
- Sent
- Included on matching requests automatically.
- Limit
- Users can read and change their own cookies.
Questions worth carrying
What are third-party cookies?
Cookies belonging to a different site from the one in your address bar, often ad or tracking services. Browsers increasingly block them.
Can JavaScript read cookies?
Yes, through `document.cookie`, unless the cookie is HttpOnly. Session cookies should be HttpOnly.