Can't share socket session between express and socket.io - node.js

I'm trying to share an express-session with socket.io session but am not able to access the saved session variables from my express routes. I'm using express-socket.io-session to share the session. When I save data on the socket's "connection" event, and then trigger a route change, express seems unaware of the changed session data.
const path = require('path');
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const session = require('express-session')({
secret: 'secret',
resave: true,
saveUninitialized: true
});
var sharedsession = require('express-socket.io-session');
app.use(session);
io.use(sharedsession(session, {
autoSave: true
}))
io.on('connection', (socket) => {
socket.handshake.session.data = ['connection']
console.log(socket.handshake.session);
// First
socket.on('login', data => {
socket.handshake.session.data.push('login');
console.log(socket.handshake.session);
});
})
// Second
app.get('/route', (req, res, next) => {
console.log(req.session.data); // => undefined
})
app.get('/*', (req, res, next) => {
res.sendFile(path.join(__dirname, 'index.html'));
})
server.listen(3000);
I've spent a lot of time troubleshooting with different configuration options with no success. The best way for me to demonstrate the problem by creating an extremely minimal example in a repo:
https://github.com/matt-mcdaniel/express-socket-test
Why can't I access the saved data from my socket connection in my express routes?

I think you are missing the .save() method when you are setting a value in session from socket io like this -
socket.handshake.session.data = ['connection'];
socket.handshake.session.save();
This should work probably.

Related

Have a cookie get deleted as soon as I leave the page on node

I am setting a cookie as soon as users access my node app like this:
app = require("express")();
httpServer = require("https").createServer(options,app);
cookie = require("cookie");
app.get('/site', function (req, res, next) {
res.sendFile(__dirname + '/index.html');
res.cookie('active', 1, {
httpOnly: true
});
});
the cookie is stored so that just works fine. However, I want the cookie to be destroyed as soon as the user closes the browser, window, tab, etc. but its not. Why is that?
Thank you.
As per cookie package example can you try following for your code ?
const app = require("express")();
const httpServer = require("https").createServer(options,app);
const cookie = require("cookie");
app.get('/site', function (req, res, next) {
res.setHeader('Set-Cookie', cookie.serialize('active', String(1), {
httpOnly: true
}));
res.sendFile(__dirname + '/index.html');
});

How to prevent routes from being called multiple time in express.js

I am new to node.js and I am trying to make a simple task list app using express.js and express-session. However, for a reason that I don't understand most of the routes are called two or tree times when I make a request and it shouldn't. For instance, if I send a request to /new the new task is sometimes added two (or three) times instead of one and this causes a problem...
I read in other threads that the problem could come from the browser trying to get a favicon, however if I log all incoming request url (console.log(req.url)) on the /new route, the duplicated requests are always /new and not a favicon...
Here is my code :
var express = require('express');
var session = require('express-session');
// Create a new express application instance
var app = express();
// Initialize session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: {}
}));
// Initialize req.session.tasks if needed
app.use(function (req, res, next) {
if (req.session.tasks === undefined) {
req.session.tasks = [];
}
next();
});
app.get('/', function (req, res) {
res.send(req.session.tasks);
});
// Create a Test Task
app.get('/new', function (req, res) {
console.log(req.url);
req.session.tasks.push("Test Task");
res.redirect('/');
});
app.get('/clear', function (req, res) {
req.session.tasks = [];
res.redirect('/');
})
app.listen(3000, function () {
console.log('Task Server is listening on port 3000!');
});
Do you have a idea of what could be the cause of this problem and how to avoid it ??
Thanks a lot !

Node Express setting cookies

I may be misunderstanding here.
I have a node server running at localhost:3000, and a React app running at localhost:8080.
The React app is making a get request to the node server - my server code for this looks like:
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(cookieParser());
app.get('/', function (req, res) {
let user_token = req.cookies['house_user']; // always empty
if (user_token) {
// if the token exists, great!
} else {
crypto.randomBytes(24, function(err, buffer) {
let token = buffer.toString('hex');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: false });
res.send(token);
});
}
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
I'm trying to set the house_user token, so that I can later keep track of requests from users.
However, the token is not being set on the user (request from localhost:8080) - the house_user token is always empty (in fact, req.cookies is entirely empty). Do I need to do something else?
I just tried the code below (and it worked). As a reminder, you can just paste this in myNodeTest.js, then run node myNodeTest.js and visit http://localhost:3003. If it does work, then it probably means you're having CORS issues.
[EDIT] withCredentials:true should do the trick with axios.
axios.get('localhost:3000', {withCredentials: true}).then(function (res) { console.log(res) })
const express = require('express')
const cookieParser = require('cookie-parser')
const crypto = require('crypto');
const port = 3003
app.use(cookieParser());
app.get('/', function (req, res) {
let user_token = req.cookies['house_user']; // always empty
if (user_token) {
// if the token exists, great!
} else {
crypto.randomBytes(24, function(err, buffer) {
let token = buffer.toString('hex');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.cookie('house_user', token, {maxAge: 9000000000, httpOnly: true, secure: true });
res.append('Set-Cookie', 'house_user=' + token + ';');
res.send(token);
});
}
});
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
Making my comment into an answer since it seemed to have solved your problem.
Since you are running on http, not https, you need to remove the secure: true from the cookie as that will make the cookie only be sent over an https connection which will keep the browser from sending it back to you over your http connection.
Also, remove the res.append(...) as res.cookie() is all that is needed.

Express websockets on message get cookie info

I have an express web socket application.
In the onmessage function, I would like to access the cookies of the client that sent the message.
The reason for this is that I'm making a game and I have the user login. I need to check what to name cookie is so that I control the correct player.
This is what I've got so far:
var express = require('express');
var expressWs = require('express-ws');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(cookieParser('secretkey123'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
expressWs = expressWs(app);
app.get('/', function(req, res) {
// stuff for logging in
})
app.post('/', function(req, res) {
// stuff for logging in
})
app.get('/logout', function(req, res) {
res.clearCookie('name');
res.redirect('/');
// more stuff for logging in
})
app.ws('/ws', function(ws, req) {
ws.on('open', function() {
// how do I check when a connection is opened?
})
ws.on('message', function(msg) {
// who sent the message? how do I get the cookie info to check the user who send it?
})
ws.on('close', function() {
// the've disconnected
})
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
})
Is this possible?
Also, where do I check when a websocket connection is opened?
I tried the 'open' event but it doesn't seem to be working.
Thanks for the help in advance!
I figured out how to do it!
I forgot that the req argument can be accessed inside the other functions.
This means in the on message function you can just do this:
ws.on('message', function(msg) {
req.cookies.username //do stuff
});
The connection open code can be done before you setup any of the events:
app.ws('/ws', function(ws, req) {
// connection open code here
ws.on('message', function(msg) {
// connection message code here
})
})

ExpressJS & Websocket & session sharing

I'm trying to make a chat application based on Node.js. I'd like to force websocket server (ws library) to using ExpressJS session system. Unfortunately, I've got stuck. MemoryStore hashes used to get sessions' data are different than session IDs in cookies. Could somebody explain me what I'm doing wrong?
Websocket server code part:
module.exports = function(server, clients, express, store) {
server.on('connection', function(websocket) {
var username;
function broadcast(msg, from) {...}
function handleMessage(msg) {...}
express.cookieParser()(websocket.upgradeReq, null, function(err) {
var sessionID = websocket.upgradeReq.cookies['sid'];
//I see same value in Firebug
console.log(sessionID);
//Shows all hashes in store
//They're shorter than sessionID! Why?
for(var i in store.sessions)
console.log(i);
store.get(sessionID, function(err, session) {
websocket.on('message', handleMessage);
//other code - won't be executed until sessionID in store
websocket.on('close', function() {...});
});
});
});
}
store object definition:
var store = new express.session.MemoryStore({
reapInterval: 60000 * 10
});
app configuration:
app.configure(function() {
app.use(express.static(app.get("staticPath")));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: store,
secret: "dO_ob",
key: "sid"
}));
});
Part of main code:
var app = express();
var httpServer = http.createServer(app);
var websocketServer = new websocket.Server({server: httpServer});
httpServer.listen(80);
Sample debugging output:
- websocket.upgradeReq.headers.cookie "sid=s%3A64a%2F6DZ4Mab8H5Q9MTKujmcw.U8PJJIR%2BOgONY57mZ1KtSPx6XSfcn%2FQPZ%2FfkGwELkmM"
- websocket.upgradeReq.cookies["sid"] "s:64a/6DZ4Mab8H5Q9MTKujmcw.U8PJJIR+OgONY57mZ1KtSPx6XSfcn/QPZ/fkGwELkmM"
- i "64a/6DZ4Mab8H5Q9MTKujmcw"
I found this works for me. Not sure it's the best way to do this though. First, initialize your express application:
// whatever your express app is using here...
var session = require("express-session");
var sessionParser = session({
store: session_store,
cookie: {secure: true, maxAge: null, httpOnly: true}
});
app.use(sessionParser);
Now, explicitly call the session middleware from the WS connection. If you're using the express-session module, the middleware will parse the cookies by itself. Otherwise, you might need to send it through your cookie-parsing middleware first.
If you're using the websocket module:
ws.on("request", function(req){
sessionParser(req.httpRequest, {}, function(){
console.log(req.httpRequest.session);
// do stuff with the session here
});
});
If you're using the ws module:
ws.on("connection", function(req){
sessionParser(req.upgradeReq, {}, function(){
console.log(req.upgradeReq.session);
// do stuff with the session here
});
});
For your convenience, here is a fully working example, using express, express-session, and ws:
var app = require('express')();
var server = require("http").createServer(app);
var sessionParser = require('express-session')({
secret:"secret",
resave: true,
saveUninitialized: true
});
app.use(sessionParser);
app.get("*", function(req, res, next) {
req.session.working = "yes!";
res.send("<script>var ws = new WebSocket('ws://localhost:3000');</script>");
});
var ws = new require("ws").Server({server: server});
ws.on("connection", function connection(req) {
sessionParser(req.upgradeReq, {}, function(){
console.log("New websocket connection:");
var sess = req.upgradeReq.session;
console.log("working = " + sess.working);
});
});
server.listen(3000);
I was able to get this working. I think you need to specify the secret on cookieParser instead of session store.
Example from my app:
var app = express();
var RedisStore = require('connect-redis')(express);
var sessionStore = new RedisStore();
var cookieParser = express.cookieParser('some secret');
app.use(cookieParser);
app.use(express.session({store: sessionStore}));
wss.on('connection', function(rawSocket) {
cookieParser(rawSocket.upgradeReq, null, function(err) {
var sessionID = rawSocket.upgradeReq.signedCookies['connect.sid'];
sessionStore.get(sessionID, function(err, sess) {
console.log(sess);
});
});
});
Feb 2022 update:
verifyClient is now discouraged. New methods of doing this is described in an issue comment.
Consult the example code for session parsing and verification for a full usage example. Sample of the verification function:
server.on('upgrade', function (request, socket, head) {
console.log('Parsing session from request...');
sessionParser(request, {}, () => {
if (!request.session.userId) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
console.log('Session is parsed!');
wss.handleUpgrade(request, socket, head, function (ws) {
wss.emit('connection', ws, request);
});
});
});
Original answer:
In version 3.2.0 of ws you have to do it a bit differently.
There is a full working example of express session parsing in the ws repo, specifically using a new feature verifyClient.
A very brief usage summary:
const sessionParser = session({
saveUninitialized: false,
secret: '$eCuRiTy',
resave: false
})
const server = http.createServer(app)
const wss = new WebSocket.Server({
verifyClient: (info, done) => {
console.log('Parsing session from request...')
sessionParser(info.req, {}, () => {
console.log('Session is parsed!')
done(info.req.session.userId)
})
},
server
})
wss.on('connection', (ws, req) => {
ws.on('message', (message) => {
console.log(`WS message ${message} from user ${req.session.userId}`)
})
})
WS v3.0.0 and above, has changed the behaviour so the given answers won't work out of the box for those versions. For current versions, the signature of the connection method is [function(socket, request)] and the socket no longer contains a reference to the request.
ws.on(
'connection',
function (socket, req)
{
sessionParser(
req,
{},
function()
{
console.log(req.session);
}
);
}
);
Currently, below is my workaround which is working fine. I just don't know it's disadvantages and security. I just prevent the server from listening if it doesn't have a session. (Share session from express-session to ws)
I haven't fully tested this though.
var http = require('http');
var express = require('express');
var expressSession = require('express-session');
var router = express.Router();
var app = express();
const server = http.createServer(app);
router.get('/', function(req, res, next) {
if(req.session.user_id) {
// Socket authenticated
server.listen(8080, function listening(){});
}
});

Resources