Authentication foundations

Set a secure session cookie

Use HTTPS and restrictive cookie attributes so scripts, insecure transport, and unnecessary cross-site requests cannot expose the session.

8 minute lesson

~~~

A session identifier is temporarily equivalent to the authentication proof that created it. Protect it as a credential.

Use an HttpOnly, Secure, appropriately SameSite cookie, no broad Domain, and a controlled lifetime. A __Host- name adds browser-enforced restrictions when its requirements are met. It requires Path=/, so choose the host-bound prefix or narrower path scoping deliberately rather than claiming both. Serve the entire authenticated application over HTTPS.

Set-Cookie: __Host-session=opaque-random-value; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600

Each attribute solves a different problem:

  • HttpOnly prevents ordinary browser JavaScript from reading the value.
  • Secure sends it only over HTTPS.
  • SameSite limits some cross-site requests.
  • Path=/ makes a __Host- cookie available to the whole origin.
  • omitting Domain keeps subdomains from setting or receiving it.

These controls reduce exposure. They do not replace server validation, CSRF protection, or XSS prevention. Injected code may be unable to read an HttpOnly cookie but can still submit authenticated actions from the page.

Expire the browser cookie and revoke the server record on logout. Clearing only the cookie leaves a copied token valid. Revoking only the record is safe, but the browser keeps sending a useless credential until it expires.

Set the cookie through an HTTPS-capable development environment or use a documented local exception without weakening production. Inspect its flags and scope in DevTools, revoke the server record, and confirm the next request fails.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →