I want to develop a node.js app with express. The application is going to support multiple access levels. All users will be authenticated through username & password. The authentication method that I've been using until now is the following:
How secure is this process? Does it use cookies? Does it have vulnerabilities? Is it more secure to control sessions through websockets and socket.io or any other different way? Thanks in advance
Session in express will use cookies if you will setup so. It will exchange long key that is used in order to trigger session restore on server side.
Session data on server side is not shared with client through cookies. You can verify this in response Headers of a request to page with session enabled on server side.
Socket.IO have ability to restore session data during handshake process as it starts as normal HTTP request and does exchange cookie as well which is used to verify identity of user additionally to another validations for session restoring.
This is well efficient and secure to do as far as stolen cookies will not give ability to access from another remote end point and browser.
In order to make different user types with different access restriction I've used middleware functions that are very handy in routes declaration.
From coding point of view they might look like that:
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 same function as last function that accepts req
, res
and next
, so you can have access to session data from it and can call next()
in case if valid, or next(new Error('reason'));
that will not continue chain of middleware to last function, but will pop out to route that handles errors.
If you have chain of routes that should try to fallback, then instead of returning next(new Error());
you might want to have flag of allowed
in req
somewhere, and then check in last route callback to check if it is allowed
if not - call next()
that will try to find another route that suits the query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With