socket.io parse connect (>= 2.4.1) signed session cookie
Asked Answered
S

1

12

With the latest version of connect (as of 2012-07-26), I've found the following way to get a session ID from socket.io that will work with a connect-redis store.

var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');

var secret = '...';
var rStore = new(require('connect-redis')(express));

//...

var server = http.createServer(app);
var sio = io.listen(server);

sio.set('authorization', function(data, accept) {
    if(data.headers.cookie) {
        data.cookie = cookie.parse(data.headers.cookie);
        data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
    } else {
        return accept('No cookie transmitted', false);
    }
    accept(null, true);
});

data.sessionID can then be used later such as

sio.sockets.on('connection', function(socket) {
    console.log('New socket connection with ID: ' + socket.handshake.sessionID);
    rStore.get(socket.handshake.sessionID, function(err, session) {
        //...
    });
});

Having to import so many from express (connect, a utility of connect, and the cookie module) seems like an overly roundabout way of getting the functions needed to parse connect's signed cookies. Has anyone found another way?

Shadowy answered 27/7, 2012 at 3:19 Comment(1)
I wish I could upvote this 100+ times. Your solution above saved me lots of time, thank you for posting it! I'm sorry I can't suggest another way.Uranian
M
6

I was running into the same and just wrote a tiny module to abstract it. Here's how its usage looks like. It was written and tested using express 3 so should work fine with connect 2.4.x. Please let me know otherwise.

var SessionSockets = require('session.socket.io')
  , sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

sessionSockets.on('connection', function (err, socket, session) {
  //your regular socket.io code goes here
});

For more details on how it works see https://github.com/wcamarao/session.socket.io

Mckellar answered 10/9, 2012 at 5:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.