Track 07 · Lesson 11 of 18Identity and login

Track 07 · Identity and login

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

Flip one bit in an AES-GCM sealed cookie and send it. What happens?