Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, ws and express-session : how to get session object from ws.upgradeReq

I have an application built on express, express-session and ws ( for the websocket support).

I have used this code to enable the session middleware:

app.use(session({secret: 'mysecret',resave: true,saveUninitialized: true,cookie: {}}));

And I can read and save session variables within a get handler with:

app.get('/', function (req, res) {
  res.send('Hello World!');
  console.log(req.session.test);
  req.session.test="OK";
  req.session.save();
});

(the first time it prints "undefined" and the second time it prints "OK" as expected)

Now I have a websocket server that is handled by express too in the same app and I would like to get the req.session object inside the ws.on("connection",...) and in ws.on("message",...).

The problem is that there is no reference to the original req object, just a reference to a upgradeReq that is a wrapper of the connection handler of the websocket. Inspecting this upgradeReq I can find the connect.sid in ws.upgradeReq.headers.cookie that contains the session cookie value.

wss.on('connection', function connection(ws) {
  var location = url.parse(ws.upgradeReq.url, true);
  console.log(ws.upgradeReq.headers.cookie);
  //....
});

In my idea could be possible to get the original req.session from this in some way.

How can I accomplish this ?

like image 685
alexroat Avatar asked Apr 25 '16 13:04

alexroat


1 Answers

I just found out that at version 3.0.0 upgradeReq was removed from WebSocket. A workaround for existing code of alexroat:

wss.on('connection', function connection(ws, req) {
    ws.upgradeReq = req;
    var location = url.parse(ws.upgradeReq.url, true);
    //get sessionID
    var cookies = cookie.parse(ws.upgradeReq.headers.cookie);
    var sid = cookieParser.signedCookie(cookies["connect.sid"], secret);
    //get the session object
    store.get(sid, function (err, ss) {
        //create the session object and append on upgradeReq
        store.createSession(ws.upgradeReq, ss)
        //setup websocket bindings
        ws.on('message', function incoming(message) {
            console.log('received: %s', message);
            //..........
        });
    });
});
like image 170
dritan Avatar answered Sep 19 '22 19:09

dritan