Menu

Signed-Cookie Sessions Without a Login (HMAC in About 40 Lines)
📰

Signed-Cookie Sessions Without a Login (HMAC in About 40 Lines)

DEV Community: typescript·Royal Simpson Pinto·18 days ago
#Ef4Kai2w
#devtotypescript#devto#dev#session#payload
Reading 0:00
15s threshold

Not every app needs a login. Sometimes you just want each visitor to have a stable handle so a leaderboard, a draft, or a rate limiter can tell them apart. Building full auth for that is overkill. But you also cannot just trust a plain nickname cookie, because the browser owns that cookie and anyone can edit it.

The middle ground is a signed cookie session : you put a small piece of identity in a cookie, sign it with an HMAC using a server-only secret, and verify the signature on every request. The client can read the cookie, but it cannot forge a valid one. I use exactly this in injection-arena , a prompt-injection game where players need a persistent identity for the leaderboard but I never wanted to run an accounts system. Let me walk through the technique.

The shape of the thing

A signed cookie value is two parts glued together:

base64url(payload) . signature

Enter fullscreen mode

Exit fullscreen mode

The payload is your identity data as JSON. The signature is HMAC-SHA256(payload, secret) .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.