expresssessionbackbone.jsxmlhttprequest

Express.js 3 creates new sessions with each XHR request from Backbone.js


I have a Backbone app that queries my Express server with a un/pw, authenticates, then sends the account info (from MongoDB) along with the new sessionID back to the client. When i need more data, i attach the session id to the .fetch() options. However, Express creates a new session, even though my session was stored in Redis successfully.

Here is the middleware that checks if the client is trying to work with my api

var _restrictApi = function(req, res, next) {
  if (req.url.match(/api/)) {
    res.xhrAuthValid = req.param('sessionId') == req.sessionID;
    if (res.xhrAuthValid || (req.method=='GET' && req.url.match(/api\/account/))) {
      console.log('API access granted', req.url);
      console.dir(req.session);
      next();
    } else {
      console.log('API access BLOCKED', req.url);
      console.log(req.param('sessionId'), req.sessionID);
      console.dir(req.session);
      res.send(403, 'Forbidden');
    }
  } else {
    next();
  }
};

My Backbone app makes a few .fetch() calls upon loading. First, log-in, then grab events for the user. Here is the Express server console log:

API access granted /api/account?email=test%40gmail.com&password=somepw
{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }
_checkAccount test@gmail.com
pw matches
{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  account: 
   { _id: 500471eb8bfff124ce984917,
     dtAdd: '2012-07-16T20:07:58.671Z',
     email: 'test@gmail.com',
     pwHash: '$2a$10$2KJXrZeAGW58Kp9JQDL9B.K2Fvu2oE3oqWKRl55o8MeXGHA/zCBE.',
     sessionId: 'iqYjOA7CeQHny9cm8zOWERjv' } }
API access BLOCKED /api/events?accountId=500471eb8bfff124ce984917&sessionId=iqYjOA7CeQHny9cm8zOWERjv
iqYjOA7CeQHny9cm8zOWERjv rsSXKtzXNNiq8x3+pUN9JXWF
{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }

Solution

  • Create a connect.sid by signing the sessionID:

    cookie = require('cookie-signature')
    res.send('connect.sid=s%3A'+cookie.sign(req.sessionID, req.secret))
    

    Store it in local storage and set the Cookie header for each AJAX request:

    r.setRequestHeader('Cookie', window.localStorage['connect.sid'])
    

    That works.