Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict access to Node.js using Express

I do have a running node.js script located in a server. What i want is that it doesn't get directly accessed from browser and also i want that only certain domains/IP-s can call it! Is it possible?!

like image 825
J Mon Avatar asked Feb 05 '16 23:02

J Mon


People also ask

How do you protect Express routes?

The ensureAuthenticated function is just an example, you can define your own function. Calling next() continues the request chain. No idea, if you want to protect a set path you can use middleware e.g app. use('/user/*', ensureAuthenticated) will protect any matching routes.

What is Express () in NodeJS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

Can NodeJS work without Express?

It's possible to use NodeJS alone. But, you have to write more code that is provided by express or any other framework.


1 Answers

Not sure how to distinguishing between accessing something from a browser as opposed to other software, but restricting access to some domains/IPs should be doable. The following (non production) code to restrict access to the localhost loop back might serve as a starting point:

function securityCheck( req, response, next)
{    var callerIP = req.connection.remoteAddress;
     (callerIP == "::ffff:127.0.0.1" || callerIP == "::1") ? next() : reply404( response);
}

function reply404( response)
{   response.writeHead(404, {"Content-Type": "text/html"});
    response.statusMessage = "Not Found";
    console.log("reply404: statusCode: " + response.StatusCode);
    response.end('<span style="font-weight: bold; font-size:200%;">ERROR 404 &ndash; Not Found<\/span>');
}
var app = express();
app.use(securityCheck);  // restrict access
... // continue with app routing

See also more detailed SO answers to Express.js: how to get remote client address and How do I get the domain originating the request in express.js?

like image 138
traktor Avatar answered Sep 22 '22 10:09

traktor