29

How can I restrict access by IP address in a Node.js HTTP server application?

I'm looking for something like this:

Deny from all
Allow from ..

I need to allow access to the site for only a few IP addresses. How can I do this?

Brad
  • 159,648
  • 54
  • 349
  • 530
Vitalii Maslianok
  • 1,601
  • 1
  • 14
  • 16

2 Answers2

37

I'm not sure how bulletproof is this approach, but here it is, collected from answers around the web:

var http = require('http');
http.createServer(function (req, res)
{
    var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    if (ip == '127.0.0.1') // exit if it's a particular ip
        res.end();
...

Please, someone more proficient in node - correct me

Travis
  • 12,001
  • 8
  • 39
  • 52
Alex K
  • 6,737
  • 9
  • 41
  • 63
30

If you are restricting access to the entire server by network address, it is best to put those rules in your firewall. If you want to handle it at the application layer for some reason (ease of configuration, dynamic authorization, etc.) then it is best to do this immediately upon connection rather than waiting for an HTTP request.

Node.js' http.Server emits a connection event which you can use to determine the remote address and kill the connection before (or during) the actual HTTP request. This code is untested but should get you started:

var server = http.createServer(function (req, res) {
  // Your normal request handling goes here
});

server.on('connection', function (sock) {
  console.log(sock.remoteAddress);
  // Put your logic for what to do next based on that remote address here
});

server.listen(80);
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 1
    Very good point. I currently use a system where I log the ip's from nodejs and have a shell script running periodically to update iptables respectively. You're definitely correct when you said 'put those rules in your firewall, before it hits the application layer'. – NiCk Newman Jul 18 '15 at 19:50