Link Search Menu Expand Document

Broken Authentication in NodeJS

Vulnerable example

Node.js does not provide a native way to implement a robust web application authentication system.

The following Express.js route is an example of an endpoint that is available to anyone; it does not enforce any authentication:

app.post('/admin', function (req, res) {
    // perform some sensitive action
});

The /admin endpoint is available to everyone and should be protected by an authentication mechanism so as not to be abused by malicious actors.

Prevention

Apply the recommended authentication and authorization mechanisms depending on the web framework of choice.

Express.js

Express.js allows for the implemention of authentication as a middleware. In this case, one could implement an authentication middleware and (re)use it for one or more routes. For example, the following middleware checks the value of a session variable:

function authenticate(req, res, next) {
    if (!req.session.isLoggedIn) {
        res.redirect('/index.html');
    } else {
        next();
    }
}

It is possible to plug the authentication check in a route as shown below:

app.post('/admin', authenticate, function (req, res) { /*...*/ });

References

CWE-285 - Improper Authorization CWE-287 - Improper Authentication OWASP - Testing for Bypassing Authentication Schema (OTG-AUTHN-004)