Jagadeesh
Jagadeesh

Reputation: 2097

How to do whitelist of IP's in Express?

I need to block every IP address from accessing my site except one or two IP's provided by myself. I have tried many modules but nothing seems to work.

var express = require('express')
var AccessControl = require('express-ip-access-control');
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

var middleware = AccessControl(options);
 app.use(AccessControl(options));

var options = {
    mode: 'deny',
    denys: [],
    allows: ['**8.1**.1.**'],
    forceConnectionAddress: false,
    log: function(clientIp, access) {
        console.log(clientIp + (access ? ' accessed.' : ' denied.'));
    },

    statusCode: 401,
    redirectTo: '',
    message: 'Unauthorized'
};

app.listen(3000, function () {
  console.log(' app listening on port 3000!')
})

on running and accessing my site from my above code i am getting the console message as

::ffff:127.0.0.1 accessed.
::ffff:127.0.0.1 accessed.
::ffff:127.0.0.1 accessed.
::ffff:127.0.0.1 accessed.

any help?

Upvotes: 4

Views: 17828

Answers (2)

jabe
jabe

Reputation: 834

You can simply add your own middleware that checks the IPs, no need to include another module.

You can see the ip from the request with req.connection.remoteAddress.

Before you define your routes, add something like this:

// Custom Middleware
app.use((req, res, next) => {
let validIps = ['::12', '127.0.0.1']; // Put your IP whitelist in this array

  if(validIps.includes(req.connection.remoteAddress)){
      // IP is ok, so go on
      console.log("IP ok");
      next();
  }
  else{
      // Invalid ip
      console.log("Bad IP: " + req.connection.remoteAddress);
      const err = new Error("Bad IP: " + req.connection.remoteAddress);
      next(err);
  }
})

This will throw an error if an invalid ip comes in. Below all your routes, add something like this:

// Error handler
app.use((err, req, res, next) => {
    console.log('Error handler', err);
    res.status(err.status || 500);
    res.send("Something broke");
});

Upvotes: 6

You need to define your options before you use them. Otherwise, you're passing in undefined to app.use(AccessControl(options)).

Not sure how this is compiling for you, but adding the following line to the top of your script might help show a few more errors that would help.

'use strict';

Secondly, according to the express-ip-access-control documentation:

'allow' mode (Whilelist):

Deny by default, only allow IPs in the whitelist (allows) and not excluded by the blacklist (denys).

So change options.mode from 'deny' to 'allow'.

Upvotes: 3

Related Questions