Link Search Menu Expand Document

Broken Authorization in NodeJS

Prevention

Node.js does not provide any native authentication and authorization mechanism that can be implemented using sessions. This task is often delegated to third-party frameworks and libraries.

Express.js

Being a fairly low-level framework, Express.js does not provide ready-made authentication and access control mechanisms, but its middleware-based architecture can be easily leveraged to implement simple custom solutions.

As an example, consider the following administrative endpoint:

app.use('/admin', function (req, res) {
    res.end('some administrative functionality here...');
});

This endpoint can be accessed by anyone; Express.js allows a pipeline of stages that are processed in order to serve the actual content of the endpoint logic to be specified. For example, the following middleware checks that a session is established and that the current user is an administrator:

function check_admin(req, res, next) {
    const username = req.session.user_id;
    if (!username) {
        res.redirect('/login.html?message=Please+log+in');
    } else {
        const user = db.fetchUser(username);
        if (user.is_admin) {
            next(); // next middleware stage or handler
        } else {
            res.redirect('/login.html?message=Administrators+only');
        }
    }
}

Finally, the above logic can be plugged into every endpoint or router in order to enforce the access control mechanism:

app.use('/admin', check_admin, function (req, res) {
    res.end('some administrative functionality here...');
});

References

Using Express middleware