Track 07 · Lesson 11 of 18Identity and login
- 01Authentication vs authorization
- 02Browser storage compared
- 03Sessions versus tokens
- 04Inside a JWT
- 05Access and refresh tokens
- 06Where to keep tokens
- 07Choosing a design
- 08The login lifecycle
- 09The token clock
- 10Dead or just unlucky? Refresh decisions
- 11Inside a secure session cookie
- 12Five tabs, one refresh
- 13“Log in with Google”: OAuth and PKCE
- 14Two-factor login
- 15Storing passwords
- 16Logging out properly
- 17Trade-offs and common mistakes
- 18Compare the designs
Inside a secure session cookie
Lesson 11 of 18· 8 min
A session cookie holds either a random ID (classic sessions) or real credentials (a BFF storing a refresh token). If it holds credentials, seal them with authenticated encryption, so someone who copies the value out of a log can neither read nor edit it. Then set every flag.
Seal it yourself
Real AES-256-GCM, running in your browser
Wire format: base64url( nonce 12 bytes ‖ ciphertext ‖ auth tag 16 bytes )
Press Seal to generate a real one.
Authenticated encryption#
AES-256-GCM encrypts and adds an auth tag that detects any change. Flip a single bit and opening fails outright: no garbled payload, just nothing. Seal twice with the same payload and the output changes every time, because each seal uses a fresh random nonce (reusing a nonce with the same key would let an observer forge cookies). Framework libraries like iron-session, Rails encrypted cookies, ASP.NET Data Protection and Laravel’s encrypted cookies do exactly this.
Two rules that keep it simple#
Opening never throws. Tampered, truncated, wrong key, bad JSON: all return “no session”, which every caller answers with 401 and a cleared cookie. One rule, no special cases.
One owner for set and clear. A cookie delete only works if its name, path and domain match the original. Have one function return the cookie options and use it for both, so they can never drift apart and silently leave the cookie alive.
Check yourself