Session Property not saving in session store when retrieving from socket.io - express

What I am trying to accomplish is to store the username of the current user in the session, such that it can be retrieved by socket.io.
Currently, I have the client sent its sessionId to the socket.io endpoint (via io.connect):
var socket = io.connect('http://localhost?sessionId=' + sessionid);
and then on the server side, I have:
io.use(function(socket, callback) {
if (socket && socket.handshake && socket.handshake.query && socket.handshake.query.sessionId) {
var sessionId = socket.handshake.query.sessionId;
sessionStore.get(sessionId, function(error, session) {
socket.handshake.sessionId = sessionId;
if (error) {
callback('Could not set session id with socket io authorization handshake!', false);
} else if (!session) {
callback('There was no session found during socket io authorization handshake!', false);
}
console.log(session);
socket.session = session;
callback(null, true);
});
} else {
callback('No sessionId value was provided in query string to socket io connect from client', false);
}
});
This correctly retrieves the session from the client-provided sessionid (assuming the id exists, of course).
Now, what I want to do is be able to is get the passportjs-managed username accessible from within the socketio handlers, via the session.
So, to start with, I have this code in the router controller for this endpoint:
router.get('/', Authentication.redirectIfNotAuthenticated, function(req, res) {
req.session.user = req.user;
console.log(req.session);
res.locals.sessionId = req.session.id;
res.render('mypage', { title: 'This is my page', user: req.user });
});
That console.log(req.session) does show me that the req.user has been correctly inserted into the session object and is visible. Authentication.redirectIfNotAuthenticated is using passportjs and is really simple (code included incase it is the issue):
redirectIfNotAuthenticated : function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
So...we know that the user is being inserted as a property into the session object...but when I hit one of my socketio methods:
socket.on('init', function(info) {
console.log(socket.session);
...
});
That console.log(socket.session) does not show the session that I modified in the route, but shows the "original" session object - as though I never added anything to it at all! I do know that socket.on('init'... is being called after my io.use(function.... code as detailed above (where the session is pulled from the sessionStore and saved in the socket object).
I just haven't been able to track down why the session, as stored in socket.session (as retrieved from the session store), isn't mirroring the latest changes made to the session in the router.
If anyone has any suggestions, or reasons why what I expect to see is incorrect, I would be happy to hear them!

A session scopes a connection between a dedicated client browser tab and a server.
As you did not explain why you want to store the username in the session I can base my answer only on guesses:
If you want to remember the username for later use in the session store it on the client side.
If you want to declare the user name (and other variables) to other users in the communication space the easiest way to do that is to store the data in a database (mind that databases can be in-memory, which works out to be quick). You could also fittle with files - but if you run mutliple users you will have to switch to a database anyway...
In any way there is no need to extend the scope of a session over multiple clients.

Related

How to protect routes from guests and with roles if using JWT?

On a server side I have 2 middlewares - protect (is logged in?) and restrictTo (checks user's role). These middlewares stop users or guests from performing certain actions if they are not allowed to
exports.protect = catchAsync(async (req, res, next) => {
let token;
if (
req.headers.authorization && req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
}
if (!token) {
return next(new AppError("You are not signed in!", 401));
}
const decodedToken = await promisify(jwt.verify)(
token,
process.env.JWT_SECRET
);
const currentUser = await User.findById(decodedToken.id);
if (!currentUser) {
return next(new AppError("User with such token no longer exists"));
}
req.user = currentUser;
next();
});
exports.restrictTo = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return next(new AppError("No access", 403));
}
next();
};
};
But how do I protect routes on a client side? If I'm not allowed to post a new note then I should be stopped from going to a /newnote page so I can't see and fill the form.
JWT token is stored in cookies with httpOnly flag. So I can't access the token from a Vue router. Store a user's role in Vuex? Then how do I synchronize the token state in cookies and in Vuex? If my token has been destroyed on a server side I still can have it in Vuex until I send a request to a protected endpoint.
Should I request a special auth endpoint for protected routes to check my current role using beforeEach?
Basically, you should add two things:
store the current authenticated user. By default, authUser is null. When someone logs in, authUser is an object with the user’s data. you can store this in Vuex, localStorage, etc.
create an interceptor/middleware in whatever library you are using for your api requests. If at some point you get a 401/403, it means that the current user’s session expired, or he is trying to access a protected area he shouldnt be looking at. Either way, reset the local authUser to null and redirect to login.
In Spa/mobile you dont have to worry too much about this as long as your backend is properly secured. If your authUser logic is correct, then only users with bad intentions will try to reach protected areas, whereas normal users will play by the rules and never hit a page they arent supposed to with their current privileges (assuming the UI is wired up correctly…).

bind socket.io id to user id without sessions (express, passport JWT)

I'm developing RESTful API on express, with JWT and passport for authorization. I want to implement socket.io connection for notification and signalling purposes (WebRTC session establishing). I don't want to implement standard session management, don't want to deal with cookies, but somehow I have to be able to address particular user via socket. I have event handling in all my routes, so app is aware of auth-ed requests and corresponding user ids. One approach(probably) is to create socket io group with user id, add socket to this group and emit there. (Engaging reconnection handling and checking socket existence on every subsequent request - that's way overcomplicated). I guess there should be a better approach. I also use Redis, so I can leverage that in this scheme. Any suggestion is appreciated, thank you
Well, I managed to solve that in such a manner.
Server:
import jwt from 'jwt-simple'; //I'm using ES6/Babel
module.exports = function(app) {
var io = app.get('io'); //Import io any possible way,
//here I do it like so because I set
//app.set('io', io) in my index.js
var user_id;
io.on('connection', socket => {
// Recieve encoded token from client, decode and find user id
// To do - check againt database
socket.on('auth', token => {
if (token) {
var decoded = jwt.decode(token, 'secret')
user_id = decoded.sub
socket.emit('auth', user_id);
}
})
// Join room proposed by client - user id string
socket.on('room', room => {
socket.join(room)
console.log('Server joined room...', room)
//emit message to user id from anywhere in the app
io.sockets.in(user_id).emit('message', 'what is going on, party people?');
})
})
}
client:
var token = localStorage.getItem('token');
var socket = io();
socket.on('connect', data => {
socket.emit('auth', token);
socket.on('auth', user_id => {
socket.emit('room', user_id);
})
})
Now to address specific user I can always emit to room id equal to user id, provided that user has got credentials. Even after browser refresh.
Photo: the left client has valid token in localStorage, the right one doesn't

Link socket.io ID with express and passport

The goal of my simple try is to display online user list. I mean display not socket.io ID but display user profile. When authorized user connects to my server, open socket.io channel, it is required to get his profile and send message to other connected user that new user (Name, email, etc) has being connected. I saw many examples how to do it within authorization, but it doesn't handle a disconnect. What i want to do and what i can't do in pseudocode:
var io = require("socket.io").listen(server);
io.set("authorization", function(data, callback){
// ... some code...
callback(null, true);
});
io.sockets.on('connection', function (socket) {
var UserProfile = passport.getUserProfile(socket.id)
io.sockets.emit('user_connected', {UserProfile: UserProfile, socketID: socket.id});
io.sockets.on('disconnect', function (socket) {
io.sockets.emit('user_disconnected', {socketID: socket.id});
});
});
This is a pseudocode!
My stack is overflowed. I just want to link socket.io ID and passport account together within connection. How can i do it?
I got the same problem, and my solution is the following (hopefully someone gets a better idea):
i add the username to the render call (using jade):
res.render('chatroom', {username: req.user.username});
right after connecting to socket on the client (io.connect), i emit a
message to the server, with the username as parameter, using the connect event on the client (socket.on('connect', function (data) { ... });
on the server, i store the username in an object (clients[socket.id]
= username)
after that, i get the username in every socket message by accessing
the clients object

socket.io authentication after socket established

I'm working on a small multiplayer game. I'd like to introduce authentication. I'm using Node.js and Socket.io.
When the user arrives that the main page - I want them to join the game whether they are logged in or not - but they will be unable to do anything within it (only watch).
How could I then go about authenticating the user on the already open socket?
Could I maintain the authentication still if they left the site and came back? Can you pass a cookie through a web socket?
EDIT
To further my question. One of the possible thoughts I've had is to provide the websocket connection, then when they try to login in, it passes username and password as a message to the websocket.
client.on('onLogin', loginfunction);
I could then take the username and password, check against the database, then take the session ID of the socket and pass it somewhere to say that session is authenticated to that user.
Is this secure? Could I still implement a cookie on the socket so they could come back? Is there any way within socket.io of stating that the socket is now authenticated instead of manually checking on each message received?
Cheers
This isn't actually too hard, but you're approaching it the wrong way. A couple things:
You cannot set a cookie with socket.io; you can, however, get the cookie values of any connected client at any time. In order to set a cookie, you will have to send a new http response, meaning the user must first send a new http request (aka refresh or go to a new page, which it sounds is not a possibility for you here).
Yes: socket.io is secure (to the extent that any transmitted data can be).
As such, you can do the following:
On the user's initial connection, create a cookie with a unique session ID, such as those generated from Express's session middleware. You will need to configure these not to expire on session end though (otherwise it will expire as soon as they close their browser).
Next you should create an object to store the cookie session IDs. Each time a new connect.sid cookie is set, store in your new object with a default value of false (meaning that the user has been authenticated by session, but not by logon)
On the user's login, send a socket emit to the server, where you can then authenticate the login credentials, and subsequently update the session id object you created to read true (logged in) for the current socket id.
Now, when receiving a new http request, read the cookie.sid, and check if its value in your object is true.
It should look something like the following:
var express = require('express'),
http = require('http'),
cookie = require('cookie');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret_pw',
store: sessionStore,
cookie: {
secure: true,
expires: new Date(Date.now() + 60 * 1000), //setting cookie to not expire on session end
maxAge: 60 * 1000,
key: 'connect.sid'
}
}));
var sessionobj = {}; //This is important; it will contain your connect.sid IDs.
//io.set('authorization'...etc. here to authorize socket connection and ensure legitimacy
app.get("/*", function(req, res, next){
if(sessionobj[req.cookies['connect.sid']]){
if(sessionobj[req.cookies['connect.sid']].login == true){
//Authenticated AND Logged in
}
else{
//authenticated but not logged in
}
}
else{
//not authenticated
}
});
io.sockets.on('connection', function(socket){
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].login = false;
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].socketid = socket.id;
socket.on('login', function(data){
//DB Call, where you authenticate login
//on callback (if login is successful):
sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid']] = true;
});
socket.on('disconnect', function(data){
//any cleanup actions you may want
});
});
Chris, I'm won't be able to answer since I'm not an expert on socket.io, but I can maybe try to point you in another direction that can help you - and take away some development time.
But first, a disclaimer: I work for Realtime.co and am not trying to do any sort of advertising. I work closely with developers and I'm just trying to help you by providing you an out-of-the-box solution for your problem. Also, being a gamer, I can't stay away from trying to help people getting their games out there!
Realtime uses an authentication/authorization layer in which you can provide user read/write permissions to channels. When users enters the website you can give them read only permissions to the game channel and once they login, you can then give them write permissions. This can be easily done by doing an authentication post and reconnecting to the server (it can all be done client side). I would do it server-side, though, to increase security.
Realtime has a Node.js API so you can easily integrate it with your server. Since it also has APIs for many other platforms (including mobile) and they all work the same way, you can actually have your game working in multiple platforms over the same communication layer, while having full control over channels.
Thanks for reading.
Edit:
You can read the documentation here for more info: http://docs.xrtml.org/
Socket.io has an option to pass extraHeaders. One can use that to pass a token from the client. The server would use the desired authentication algorithm to decrypt the token and get the user_id.
socket.js
import io from 'socket.io-client';
export const socket = io('https://remote-url');
export const socketAuth = () => {
socket.io.disconnect(); //This uses the same socket and disconnect with the server.
socket.io.opts.extraHeaders = {
'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
};
socket.io.opts.transportOptions = {
polling: {
extraHeaders: {
'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
},
},
};
socket.io.open(); //Opens up a new connection with `x-auth-token` in headers
};
client.js
import { socket, socketAuth } from 'utils/socket';
socket.on('unauthenticated-messages', () => {
someAction();
});
//After user logs in successfully
socketAuth();
socket.on('authenticated-messages', () => {
someAction();
});

user authentication libraries for node.js?

Are there any existing user authentication libraries for node.js? In particular I'm looking for something that can do password authentication for a user (using a custom backend auth DB), and associate that user with a session.
Before I wrote an auth library, I figured I would see if folks knew of existing libraries. Couldn't find anything obvious via a google search.
-Shreyas
If you are looking for an authentication framework for Connect or Express, Passport is worth investigating: https://github.com/jaredhanson/passport
(Disclosure: I'm the developer of Passport)
I developed Passport after investigating both connect-auth and everyauth. While they are both great modules, they didn't suit my needs. I wanted something that was more light-weight and unobtrusive.
Passport is broken down into separate modules, so you can choose to use only what you need (OAuth, only if necessary). Passport also does not mount any routes in your application, giving you the flexibility to decide when and where you want authentication, and hooks to control what happens when authentication succeeds or fails.
For example, here is the two-step process to setup form-based (username and password) authentication:
passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user from your DB (MongoDB, CouchDB, other...)
User.findOne({ username: username, password: password }, function (err, user) {
done(err, user);
});
}
));
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
// Authentication successful. Redirect home.
res.redirect('/');
});
Additional strategies are available for authentication via Facebook, Twitter, etc. Custom strategies can be plugged-in, if necessary.
Session + If
I guess the reason that you haven't found many good libraries is that using a library for authentication is mostly over engineered.
What you are looking for is just a session-binder :) A session with:
if login and user == xxx and pwd == xxx
then store an authenticated=true into the session
if logout destroy session
thats it.
I disagree with your conclusion that the connect-auth plugin is the way to go.
I'm using also connect but I do not use connect-auth for two reasons:
IMHO breaks connect-auth the very powerful and easy to read onion-ring architecture of connect. A no-go - my opinion :).
You can find a very good and short article about how connect works and the onion ring idea here.
If you - as written - just want to use a basic or http login with database or file. Connect-auth is way too big. It's more for stuff like OAuth 1.0, OAuth 2.0 & Co
A very simple authentication with connect
(It's complete. Just execute it for testing but if you want to use it in production, make sure to use https)
(And to be REST-Principle-Compliant you should use a POST-Request instead of a GET-Request b/c you change a state :)
var connect = require('connect');
var urlparser = require('url');
var authCheck = function (req, res, next) {
url = req.urlp = urlparser.parse(req.url, true);
// ####
// Logout
if ( url.pathname == "/logout" ) {
req.session.destroy();
}
// ####
// Is User already validated?
if (req.session && req.session.auth == true) {
next(); // stop here and pass to the next onion ring of connect
return;
}
// ########
// Auth - Replace this example with your Database, Auth-File or other things
// If Database, you need a Async callback...
if ( url.pathname == "/login" &&
url.query.name == "max" &&
url.query.pwd == "herewego" ) {
req.session.auth = true;
next();
return;
}
// ####
// This user is not authorized. Stop talking to him.
res.writeHead(403);
res.end('Sorry you are not authorized.\n\nFor a login use: /login?name=max&pwd=herewego');
return;
}
var helloWorldContent = function (req, res, next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}
var server = connect.createServer(
connect.logger({ format: ':method :url' }),
connect.cookieParser(),
connect.session({ secret: 'foobar' }),
connect.bodyParser(),
authCheck,
helloWorldContent
);
server.listen(3000);
NOTE
I wrote this statement over a year ago and have currently no active node projects. So there are may be API-Changes in Express. Please add a comment if I should change anything.
Looks like the connect-auth plugin to the connect middleware is exactly what I need
I'm using express [ http://expressjs.com ] so the connect plugin fits in very nicely since express is subclassed (ok - prototyped) from connect
I was basically looking for the same thing. Specifically, I wanted the following:
To use express.js, which wraps Connect's middleware capability
"Form based" authentication
Granular control over which routes are authenticated
A database back-end for users/passwords
Use sessions
What I ended up doing was creating my own middleware function check_auth that I pass as an argument to each route I want authenticated. check_auth merely checks the session and if the user is not logged in, then redirects them to the login page, like so:
function check_auth(req, res, next) {
// if the user isn't logged in, redirect them to a login page
if(!req.session.login) {
res.redirect("/login");
return; // the buck stops here... we do not call next(), because
// we don't want to proceed; instead we want to show a login page
}
// the user is logged in, so call next()
next();
}
Then for each route, I ensure this function is passed as middleware. For example:
app.get('/tasks', check_auth, function(req, res) {
// snip
});
Finally, we need to actually handle the login process. This is straightforward:
app.get('/login', function(req, res) {
res.render("login", {layout:false});
});
app.post('/login', function(req, res) {
// here, I'm using mongoose.js to search for the user in mongodb
var user_query = UserModel.findOne({email:req.body.email}, function(err, user){
if(err) {
res.render("login", {layout:false, locals:{ error:err } });
return;
}
if(!user || user.password != req.body.password) {
res.render("login",
{layout:false,
locals:{ error:"Invalid login!", email:req.body.email }
}
);
} else {
// successful login; store the session info
req.session.login = req.body.email;
res.redirect("/");
}
});
});
At any rate, this approach was mostly designed to be flexible and simple. I'm sure there are numerous ways to improve it. If you have any, I'd very much like your feedback.
EDIT: This is a simplified example. In a production system, you'd never want to store & compare passwords in plain text. As a commenter points out, there are libs that can help manage password security.
Also have a look at everyauth if you want third party/social network login integration.
Here is some code for basic authentication from one of my projects. I use it against CouchDB with and additional auth data cache, but I stripped that code.
Wrap an authentication method around you request handling, and provide a second callback for unsuccessfull authentication. The success callback will get the username as an additional parameter. Don't forget to correctly handle requests with wrong or missing credentials in the failure callback:
/**
* Authenticate a request against this authentication instance.
*
* #param request
* #param failureCallback
* #param successCallback
* #return
*/
Auth.prototype.authenticate = function(request, failureCallback, successCallback)
{
var requestUsername = "";
var requestPassword = "";
if (!request.headers['authorization'])
{
failureCallback();
}
else
{
var auth = this._decodeBase64(request.headers['authorization']);
if (auth)
{
requestUsername = auth.username;
requestPassword = auth.password;
}
else
{
failureCallback();
}
}
//TODO: Query your database (don't forget to do so async)
db.query( function(result)
{
if (result.username == requestUsername && result.password == requestPassword)
{
successCallback(requestUsername);
}
else
{
failureCallback();
}
});
};
/**
* Internal method for extracting username and password out of a Basic
* Authentication header field.
*
* #param headerValue
* #return
*/
Auth.prototype._decodeBase64 = function(headerValue)
{
var value;
if (value = headerValue.match("^Basic\\s([A-Za-z0-9+/=]+)$"))
{
var auth = (new Buffer(value[1] || "", "base64")).toString("ascii");
return {
username : auth.slice(0, auth.indexOf(':')),
password : auth.slice(auth.indexOf(':') + 1, auth.length)
};
}
else
{
return null;
}
};
A few years have passed and I'd like to introduce my authentication solution for Express. It's called Lockit. You can find the project on GitHub and a short intro at my blog.
So what are the differences to the existing solutions?
easy to use: set up your DB, npm install, require('lockit'), lockit(app), done
routes already built-in (/signup, /login, /forgot-password, etc.)
views already built-in (based on Bootstrap but you can easily use your own views)
it supports JSON communication for your AngularJS / Ember.js single page apps
it does NOT support OAuth and OpenID. Only username and password.
it works with several databases (CouchDB, MongoDB, SQL) out of the box
it has tests (I couldn't find any tests for Drywall)
it is actively maintained (compared to everyauth)
email verification and forgot password process (send email with token, not supported by Passport)
modularity: use only what you need
flexibility: customize all the things
Take a look at the examples.
A different take on authentication is Passwordless, a token-based authentication module for express that circumvents the inherent problem of passwords [1]. It's fast to implement, doesn't require too many forms, and offers better security for the average user (full disclosure: I'm the author).
[1]: Passwords are Obsolete
A word of caution regarding handrolled approaches:
I'm disappointed to see that some of the suggested code examples in this post do not protect against such fundamental authentication vulnerabilities such as session fixation or timing attacks.
Contrary to several suggestions here, authentication is not simple and handrolling a solution is not always trivial. I would recommend passportjs and bcrypt.
If you do decide to handroll a solution however, have a look at the express js provided example for inspiration.
Good luck.
There is a project called Drywall that implements a user login system with Passport and also has a user management admin panel. If you're looking for a fully-featured user authentication and management system similar to something like what Django has but for Node.js, this is it. I found it to be a really good starting point for building a node app that required a user authentication and management system. See Jared Hanson's answer for information on how Passport works.
Here are two popular Github libraries for node js authentication:
https://github.com/jaredhanson/passport ( suggestible )
https://nodejsmodules.org/pkg/everyauth
Quick simple example using mongo, for an API that provides user auth for ie Angular client
in app.js
var express = require('express');
var MongoStore = require('connect-mongo')(express);
// ...
app.use(express.cookieParser());
// obviously change db settings to suit
app.use(express.session({
secret: 'blah1234',
store: new MongoStore({
db: 'dbname',
host: 'localhost',
port: 27017
})
}));
app.use(app.router);
for your route something like this:
// (mongo connection stuff)
exports.login = function(req, res) {
var email = req.body.email;
// use bcrypt in production for password hashing
var password = req.body.password;
db.collection('users', function(err, collection) {
collection.findOne({'email': email, 'password': password}, function(err, user) {
if (err) {
res.send(500);
} else {
if(user !== null) {
req.session.user = user;
res.send(200);
} else {
res.send(401);
}
}
});
});
};
Then in your routes that require auth you can just check for the user session:
if (!req.session.user) {
res.send(403);
}
Here is a new authentication library that uses timestamped tokens. The tokens can be emailed or texted to users without the need to store them in a database. It can be used for passwordless authentication or for two-factor authentication.
https://github.com/vote539/easy-no-password
Disclosure: I am the developer of this library.
If you need authentication with SSO (Single Sign On) with Microsoft Windows user account. You may give a try to https://github.com/jlguenego/node-expose-sspi.
It will give you a req.sso object which contains all client user information (login, display name, sid, groups).
const express = require("express");
const { sso, sspi } = require("node-expose-sspi");
sso.config.debug = false;
const app = express();
app.use(sso.auth());
app.use((req, res, next) => {
res.json({
sso: req.sso
});
});
app.listen(3000, () => console.log("Server started on port 3000"));
Disclaimer: I am the author of node-expose-sspi.
slim-auth
A lightweight, zero-configuration user authentication module. It doesn't need a sperate database.
https://www.npmjs.com/package/slimauth
It's simple as:
app.get('/private-page', (req, res) => {
if (req.user.isAuthorized) {
// user is logged in! send the requested page
// you can access req.user.email
}
else {
// user not logged in. redirect to login page
}
})