Reputation: 139
first I configure cookie-parser. https://github.com/expressjs/cookie-parser
var cookieParser = require('cookie-parser');
app.use(cookieParser(secret));
Now are the cookies like sid in req.signedCookies, but I don´t need this. If I connect with socket.io I get the cookies in this way
io.sockets.on('connection', function (socket){
var cookies = socket.handshake.headers.cookie;
// example: io=AGHGDjbasdqwe7zu23h2AAAA; sid=sn$3kjsd23123asdkjdsdasd123
});
Now my problem is, how I get sid extracted from cookies and how I unsign sid? If I use
io.sockets.on('connection', function (socket){
cookieParser.signedCookie(socket.handshake.headers.cookie, secret);
});
I got the same result io=AGHGDjbasdqwe7zu23h2AAAA; sid=sn$3kjsd23123asdkjdsdasd123
Upvotes: 4
Views: 3770
Reputation: 13567
You can use io.use
to add some authentication middleware, which decodes the sid and adds it to the socket object:
io.use(function (socket, next) {
var data = socket.request;
if(!data.headers.cookie)
return next('No cookie given.', false);
cookieParser(data, {}, function(parseErr) {
if(parseErr) return next('Error parsing cookies.', false);
var sessionID = (data.secureCookies && data.secureCookies[expressSidKey]) ||
(data.signedCookies && data.signedCookies[expressSidKey]) ||
(data.cookies && data.cookies[expressSidKey]);
socket.handshake.sid = sessionID; // Add it to the socket object
});
});
Where expressSidKey
is something like express.sid
.
Upvotes: 1