How can I get (Express's) sessionID for a websocket connection
- Parse cookie
- Get session id
Get session data
var express = require('express');var parseCookie = express.cookieParser();var MemoryStore = express.session.MemoryStore;var store = new MemoryStore();app.configure(function() { app.use(express.session({ store: store, secret: '123456', key: 'sid' }));});wss.on('connection', function(ws) { parseCookie(ws.upgradeReq, null, function(err) { var sessionID = ws.upgradeReq.cookies['sid']; store.get(sessionID, function(err, session) { // session }); }); ws.on('message', function(message) { console.log('received: %s', message); }); ws.send('something');});
This was a nightmare, finally got it working for myself using signed cookies!
Set up your store (example memory store):
var MemoryStore = express.session.MemoryStore;store = new MemoryStore();
Expose parseCookie as global (if you need it in other modules) like this in app / server js files:
app.use(parseCookie = express.cookieParser('secret'));
Now set up sockets:
//this method gets called latervar ensureAuthenticatedSocket = function(handshake, callback) { cookie = cookieParser(handshake, null, function(err) { var sessionID = handshake.signedCookies['sid']; store.get(sessionID, function(err, session) { callback(err, session); }); });};//listen timeio = io.listen(server);//configure authenticationio.configure(function() { io.set('authorization', function(handshake, callback) { //call the method with handshake as parameter, wait for callback ensureAuthenticatedSocket(handshake, function(err, session) { if (!err && session) { //no error + found session = wicked! callback(null, true); } else { callback(null, false); } }); });});...//more socket code