3

I am using mongoStore to manage session on express.js framework.

...
var MongoStore = require('connect-mongo')(express);
...
...
app.use(express.session({
    secret:settings.cookieSecret,
    store: new MongoStore({db:settings.db})
}));
...

this is the connect.sid and its value

but here is the record in sessions collection on mongoDB

> db.session
s.find()
{ "_id" : "gLQe0NwaSmk9nPu6vOWKuSy0", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"flash\":{},\"user\":null}", "expires" : ISODate("2013-12-24T05:02:33.308Z") }
{ "_id" : "SoqYLZnEzlVCdj4A1606fDPg", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"flash\":{},\"user\":\"vvv\"}", "expires" : ISODate("2013-12-24T09:43:55.098Z") }
{ "_id" : "pBtoFt6sR2EvNCuPJVqAFVpR", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"flash\":{}}", "expires" : ISODate("2013-12-24T09:24:27.846Z") }
{ "_id" : "MEkFGzd190YeJAGDH3nzLT14", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"flash\":{}}", "expires" : ISODate("2013-12-24T09:44:10.585Z") }
> 

My understanding is they should store value of connect.id both on client cookie and somewhere on server db or memory. Since I am using connect-mongo, the connect.id should store in db.sessions.

But I can't find the connect.id on server side. Where do they store this value? If my understand is wrong, please correct it. Thank you!

Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129

2 Answers2

1

If you read the source code of connect-mongo, object id of Mongo's document is the session id:

var s = {_id: sid, session: this._serialize_session(session)};

in session middleware:

// get the sessionID from the cookie
req.sessionID = unsignedCookie;

However, you don't just see the cookie ID in your screenshot because a hash is appended to the cookie value (see this relevant answer) by the cookie-signature module, hence the sid.hash cookie value you're seeing.

Here is the relevant source code, where the hashed value is stored:

  // set-cookie
  val = 's:' + signature.sign(val, secret);
  val = cookie.serialize(key, val);

You can also read the unit tests for a more thorough understanding.

Community
  • 1
  • 1
Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
1

the session cookie feature of express.js is actually provided by connect

the secret key you've set is used to sign the session id from database into the value you see

Check the source code

Ryan Wu
  • 5,963
  • 2
  • 36
  • 47
  • Note that the source you've linked is deprecated: `console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature')` – Paul Mougel Dec 10 '13 at 10:29