Sam
Sam

Reputation: 6552

How does Connect's session middleware's signed cookies work?

I would like an explanation on how the connect.sid cookies work in the Connect Node.js framework. I noticed that they are formated like,

s:hash.signature

I don't understand how the signature is used when the hash is more than capable of being used to access the session data from a memory store or redis store.

Also, I don't understand why the s: is even in the cookie; what is it's purpose.

I'm hearing that the signature is used to "sign" the hash. What exactly is meant by "sign" or "signed"? I need an explanation on this process as well.

Upvotes: 4

Views: 2137

Answers (1)

Pascal Belloncle
Pascal Belloncle

Reputation: 11389

The signature is there so the server can verify that it generated the cookie, not some random attacker.

Only the person who knows the secret used to sign can sign it with the same value.

"s:" is there so it is easy to know it is a signed cookie, as opposed to some other format (like unsigned).

Here's a way to retrieve data from a signed cookie and fail is signature is incorrect. Only partial code extracted from actual app, but you should get the idea.

var cookie = require('cookie');
var connect = require('connect');
var secret = "same secret used to sign cookies";

socketio.set('authorization', function(data, cb) {
  if (data.headers.cookie) {
    var sessionCookie = cookie.parse(data.headers.cookie);
    var sessionID = connect.utils.parseSignedCookie(sessionCookie['connect.sid'], secret);
    // do something here with decoded value
  }
});

You need to use the "authorization" function from socket.io so you have access to the headers. That code works when using xhr-polling transport, I'm not sure this would work for websocket for example.

Upvotes: 5

Related Questions