The most secure node.js / express mechanism

I want to develop a node.js application with an expression. The application will support multiple access levels. All users will authenticate using a username and password. The authentication method that I have used so far is as follows:

  • The user is authenticated by username and password
  • Having set up express with session support, I use the request.session object to store all user information and credentials, and I check it every time a new call comes to the server from the same user.

How safe is this process? Does he use cookies? Does it have vulnerabilities? Is it safer to manage sessions through websockets and socket.io or any other way? thanks in advance

+7
source share
1 answer

The express session will use cookies if you configure it. It will exchange a long key, which is used to start a server-side session recovery.
Server-side session data is not transmitted to the client through cookies. You can check this in response to the request headers for a page with a server-side session enabled.
Socket.IO has the ability to restore session data during the connection process, since it starts as a normal HTTP request and also exchanges cookies, which is used to verify user identity in addition to other validations for session recovery.

This is effective and safe, because stolen cookies do not allow access from another remote endpoint and browser.

To create different types of users with different access restrictions, I used middleware functions that are very convenient in declaring routes.
From a coding point of view, they might look like this:

var userTypes = { any: function(types) { return function(req, res, next) { if (types.indexOf(req.session.user.type) != -1) { return next(); } else { return next(new Error('permission denied')); } } }, is: function(type) { return function(req, res, next) { if (req.session.user.type == type) { return next(); } else { return next(new Error('permission denied')); } } } } app.get('/items', userTypes.any([ 'developer', 'admin' ]), function(req, res, next) { // will execute if user type is developer or admin }); app.use(function(err, req, res, next) { console.log(err); res.send(err); }); 

Middleware is the same function as the last function that takes req , res and next , so you can access the session data from it and call next() if it is valid, or next(new Error('reason')); that will not continue the middleware chain for the last function, but will go on a route that handles errors.
If you have a chain of routes that should try to backtrack, instead of returning next(new Error()); , you may want to have the allowed flag in req somewhere, and then check the last route callback to check if it is allowed if not - call next() , which will try to find another route matching the request.

+7
source

All Articles