Jake Jake - 6 months ago 60
Node.js Question

How can I override the session ID for a node.js express session (using passport)

I'm implementing a passport strategy that calls our internal auth service. The internal auth service generates the session ID, so I need to make sure the connect session uses that ID instead of the default generated ID.

Is there a way to do this? Is it possible to provide my own hook function to connect to produce the session id? I can't imagine it's as simple as setting session.id or anything like that, because I don't have control over when or how connect actually creates the session.

Has anyone solved this problem?


This cannot be done with the current implementation of Connect's session middleware, but you can fork the session middleware and change how the session id is generated, namely this line:


By "fork" I mean copying the file above, changing the assignment of the sessionID and using your new file instead when configuring the session middleware.


Here's how I would regenerate the session with a custom id (note - this is just an idea, I haven't tested it):

// this is the function you'll be calling in your routes or whatever
req.regenerateSession = function(newSid) {
  // keep old session data
  var oldSessionData = req.session;

  // destroy current session and make a new one with your custom id
  store.destroy(req.sessionID, function() {
    store.generate(req, newSid);

    // copy back the session data
    // since you don't want to lose it probably
    req.session = oldSessionData;

// replace the session store generate function to accept a custom sessionID
// https://github.com/senchalabs/connect/blob/master/lib/middleware/session.js#L201
store.generate = function(req, customID) {
  req.sessionID = customID || utils.uid(24);
  req.session = new Session(req);
  req.session.cookie = new Cookie(req, cookie);