I am using SockJS on Express server. Is there any way to get the associate HTTP session ID of the client?
I see there is a way to do it for raw web socket and Socket.io, but I am struggling to find how to do it for SockJS.
This is how my server looks like. I want a similar handler to fetch session ID:
var sockjs_echo = sockjs.createServer(sockjs_opts);
sockjs_echo.on('connection', function(conn) {
conn.on('data', function(message) {
conn.write(message);
});
});
This is a "hack", but it works for me:
sockjs_echo.on('connection', function(conn) {
var cookieHeader = conn._session.recv.ws._stream._readableState.pipes._driver._request.headers.cookie
var cookies = {}
cookieHeader.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
cookies[parts.shift().trim()] = decodeURI(parts.join('='));
});
conn.on('data', function(message) {
conn.write(message);
});
});
'cookies' variable (example):
{
"dev_cookie": "1mimec6rbcolp0ujkcbqq9pdq4uoa5v0p8a284v32tmd4q3k0qi9p4vjteoifdn9b0lsm238fghf974o9jfehfuhvm3ltrgq02ad6k0",
"session_cookie": "s%3AjkKYPKFFT8r60rXUsVYISoOF17o49GUl.pbpu6T1%2BcdrIu5uQPRxZUYOrl5GnC179GaI5pWyR7SA",
"other_cookie": "s%3AzRMiC3fjo4gxTXX1p2XSi_C_EydIa358.KAdP1gwtZBVfcbkmwi%2B3pa0L1pbOCzQ3lHnNEyFvvHc"
}
Thanks so much for asking this question, #darwinbaisa, and for the answer, c-toesca. This came after days of searching.
For XHR streaming, the cookies are at: conn._session.recv.request.headers.cookie.
The only other way I could think of doing this was to make the express session cookie httpOnly: false, thus exposing it to javascript and, of course, the possibility of hacking, then pass it back as a prefix to any message from the SockJS javascript client to the node server.
Or to assign the ID to a javascript variable as I dynamically wrote a web page response, so that javascript would have access to the variable, and again could return it to the server. But again, this would have exposed the ID, and even if the ID was hashed or encrypted, it could still be used in a malicious call to the server from javascript.
Things like this are made a lot easier in the node WS library, but I need a fallback from that for websocket-challenged browsers.
Related
I use node.js, express and express-ws that is based on ws
Express-ws allows to create express-like endpoints for websockets.
I am looking for a solution to authenticate users in websocket connections, based on a token. Since my ws server is based on an HTTP one
const wsHttpServer = http.createServer();
wsHttpServer.listen(5001);
const expressWs = require('express-ws')(app , wsHttpServer);
and since the ws connection is based on an HTTP one that gets upgraded to a ws, WHY I cannot pass a token in my ws that the express route checks, like any other one? My logic is, send the token, check it, if it is ok, proceed to upgrade to a ws connection. So, I can reuse the token-middleware solution that I have in my HTTP connections.
In node
My ws server
const wsHttpServer = http.createServer();
wsHttpServer.listen(5001);
const expressWs = require('express-ws')(app , wsHttpServer);
//set the route
app.use('/ws', require('./routes/wsroute'));
In that route, I would like to use the token.validate() middleware -that in HTTP connections, checks the Authorization header
router.ws('/user/:name/:id', token.validate(), (ws, req) => {
console.log('ws route data : ',vessel, req.params.name, req.params.id);
});
In my client
const socket = new WebSocket('ws://localhost',{
path: '/user/Nick/25/',
port: 5001, // default is 80
protocol : "echo-protocol", // websocket protocol name (default is none)
protocolVersion: 13, // websocket protocol version, default is 13
keepAlive: 60,
headers:{ some:'header', 'ultimate-question':42 } // websocket headers to be used e.g. for auth (default is none)
});
this errors Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid
I also tried
const socket = new WebSocket('ws://localhost:5001/user/Nick/25', ["Authorization", localStorage.getItem('quad_token')]);
I dont get any errors, but I dont know how to get the Authorization "header" in node
I could
just send const socket = new WebSocket(currentUrl); with some data and include a valid token in that data. But to check it, I have to allow the connection first. I dont want that, I would like to use a middleware solution that automatically checks a token and allows or not to continue.
Questions
Please help me understand:
1 Is it possible to use a token-based, middleware-based solution in ws?
2 How to set a header with a token in a ws connection?
3 How to get that token in node?
1) In my experience there is no available express.js middleware and the solution i found requires to listen to the upgrade event on your http server and blocking access to your socket connection before it reaches ws routes.
2) Your browser will not allow setting additional headers during websocket connection on the client side. It will send though the cookies so you can make use of express-session to authorize on your server first the user, a cookie will be set on the browser and that cookie will be sent over during the websocket connection.
3) You can do like in this answer Intercept (and potentially deny) web socket upgrade request Copying the code here from there for your own perusal.
**wsHttpServer**.on('upgrade', function (req, socket, head) {
var validationResult = validateCookie(req.headers.cookie);
if (validationResult) {
//...
} else {
socket.write('HTTP/1.1 401 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.close();
socket.destroy();
return;
}
//...
});
As outlined here, it seems that it is not possible for a standard browser websocket client to handle a http error response to an upgrade request. Thus what I ended up using was something like this:
HTTPserver.on('upgrade' (req, sock, head) => {
if (req.url === wsRoute) {
webSocketServer.handleUpgrade(req, sock, head, ws => {
const authenticated = validateToken(req.headers.cookie) // your authentication method
if (!authenticated) {
ws.close(1008, 'Unauthorized') // 1008: policy violation
return
}
webSocketServer.emit('connection', ws, req)
})
} else {
sock.destroy()
}
}
This way we accept the connection first before closing it with an appropriate code and reason, and the websocket client is able to process this close event as required.
On your client side, you should pass an array of strings instead of object, but you must set a header for your HTTP response with a key and value:
key : headeSec-WebSocket-Protocol
value : corresponding protocol used in front.
I'm trying to implement sessions in my node.js app which makes heavy use of socket.io. I'm struggling with this currently, and found a rather simple solution which recommends using the socket itself to store the session information. For example:
socket.on('login', function(username) {
if (loginSuccessful() {
socket.sessionID = generateSessionId();
}
});
socket.on('logout', function(username) {
socket.sessionID = null;
});
I am worried that such a simple solution wouldn't be secure, however, I'm not sure if there is any clear vulnerability this solution would have.
I'm trying to test an app's socket.io which uses passport.socketio to authenticate the socket connection
var socket = require('socket.io-client')('http://localhost:' + app.PORT);
This does not work because there's no accompanying cookie.
Even if I get the cookie from a persisted superagent session
var cookie;
var agent = request.agent(app);
agent.post('/login').send('credentials').end(function(err, res) {
cookie = res.req._headers.cookie;
});
where/how do I use it ?
I found that there are already quite a few requests for socket.io-client to add cookie support
http://github.com/LearnBoost/socket.io-client/issues/450
http://github.com/LearnBoost/socket.io-client/pull/439
http://github.com/LearnBoost/socket.io-client/issues/344
but I don't see them going anywhere.
Is there any other solution to use persistent cookie session with socket while testing?
Cookie data could be passed using querystring
agent.post('/login').send('credentials').end(function(err, res) {
cookie = res.req._headers.cookie.replace(/=/g, '%3D'); //escape '='
});
socket = require('socket.io-client')('http://localhost' + '/?cookie=' + cookie);
It becomes available in the server socket
io.set('authorization', function(handshakeData, callback){
handshakeData._query.cookie;
});
And so it can be used to perform authorization. Since I was using passport.socketio, it plays nicely with a little change to check this query string instead of headers.
Building a simple app with Posts and Comments.
User hits a Post and adds a comment, everyone who's viewing that same Post will see the new comments added to the post. All done via Socket.io.
This is how I instantiate it:
// app.js
var io = require('socket.io').listen(app.listen(app.get('port')));
var chat = io.of('/p/' + id).on('connection', function(socket) {
socket.on('addComment', function(data) {
var content = data.comment;
var comment = new commentModel({
user: req.user._id,
post_id: id,
content: content
});
comment.save(function(err, doc) {
if (err) {
return next(err);
}
commentModel.findById(doc._id).populate('user').exec(function(err, comment) {
chat.emit('newComment', {
comment: comment
});
});
});
});
});
// client-side JS
self.socket_io = io.connect(window.location.href);
self.socket_io.on('newComment', function(data) {
// do stuff with the new comment
};
The first time you hit the page, the comment is submitted once (one socket connection), however, if I refresh the page and submit a new comment, two are created (one for each connected client).
Any ideas where I'm going wrong?
does
commentModel.findById
nede to be
comment.findByID
?
You could try a few of these:
Manage the socket session on the server: socketio_session[user_id].push(session).
Will give you access to all the sessions connected for a particular user. You probably don't need to store a list of sessions per user, just the latest session, and force disconnect on the existing session, before storing a new session.
--
This list a few things, including changing a config for forcing new connection
https://github.com/LearnBoost/socket.io/issues/474
--
This might also be of use, explains how to extract session id in sockets using express:
http://www.danielbaulig.de/socket-ioexpress/
I think this one might help you out creating new socket connection each time user refresh
https://github.com/wcamarao/session.socket.io/
Now, after some hours of playing around with nodejs and socket.io, I'm getting a couple more problems - one being, that I need to get the sessionID inside node.js, whitout using app.get('/' ... - since that event doesnt seem to fire when socket.io connects, it only fires .on('connection', function( ...
var express = require('express')()
express.set('port', process.env.PORT || 8080)
var server = require('http').createServer(express)
var socket = require('socket.io').listen(server)
server.listen(express.get('port'))
// this event is fired, get('/', ... isnt!
server.on('connection', function(stream) {
// ??
} )
The Session is initially created by the PHP application, as the user logs in. Session data is stored in the database, and the key I need to access that data is the SESSION ID. What's the easiest way to get to it? Like mentioned, I found a couple examples that used app.get('/' ... but I couldnt get that event to fire at all.
Thanks.
If the session data is being stored as a cookie (most likely), then you should be able to re-parse that data during the socket handshake. I posted code for that on this answer, but copied the code here as well:
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
var cookie = handshakeData.headers.cookie;
// parse the cookie to get user data...
// second argument to the callback decides whether to authorize the client
callback(null, true);
});
});
If the session data is being propagated in the URL, then you may be able to gather this information from handshakeData.url or handshakeData.query. You'll probably have to do your own experimentation.