What are "signed" cookies in connect/expressjs?

Merc picture Merc · Aug 10, 2012 · Viewed 53.6k times · Source

I am trying to figure out what "signed cookies" actually are. There isn't much on the net, and if I try this:

app.use(express.cookieParser('A secret'));

But still... Cookies are still 100% normal on the browser, and I don't really know what "signed" is here (I was sort of hoping to "see" some weirdness on the client, something like the data encrypted using "A secret" as salt?)

The documentation says (https://github.com/expressjs/cookie-parser):

Parse Cookie header and populate req.cookies with an object keyed by the cookie names. Optionally you may enabled signed cookie support by passing a secret string, which assigns req.secret so it may be used by other middleware.

Does anybody know?

Merc.

Answer

staackuser2 picture staackuser2 · Aug 10, 2012

The cookie will still be visible, but it has a signature, so it can detect if the client modified the cookie.

It works by creating a HMAC of the value (current cookie), and base64 encoded it. When the cookie gets read, it recalculates the signature and makes sure that it matches the signature attached to it.

If it does not match, then it will give an error.

If you want to hide the contents of the cookie as well, you should encrypt it instead (or just stores it in the server side session). I'm not sure if there is middleware for that already out there or not.

Edit

And to create a signed cookie you would use

res.cookie('name', 'value', {signed: true})

And to access a signed cookie use the signedCookies object of req:

req.signedCookies['name']