Block public access to expressjs app
Asked Answered
D

3

5

Consider, the following expressjs app:

var express = require('express');
var http    = require('http');
var httpApp = express();

httpApp.configure(function() {
    httpApp.use(express.static(__dirname + '/static/'));
});

var server = http.createServer(httpApp).listen(4444);

now, i want this server not to be available publically & ONLY to respond to requests from specific clients based on their IP address/domain. Everybody else should get 403 - Forbidden error.

I searched the API Doc & found way to do this to first enable trust proxy by app.enable('trust proxy') & then check req.ip.

However, I can't I access req object. so if anyone take this code & can show me how deny a req based on its IP/domain, that would be super-helpful

Dreadful answered 6/7, 2013 at 9:6 Comment(0)
K
9

Simply add a piece of middleware that checks the IP and denies access if it doesn't match:

app.use(function(req, res, next) {
  if (allowed(req.ip))
    next();
  else
    res.status(403).end('forbidden');
});
Kin answered 6/7, 2013 at 9:43 Comment(0)
B
1

Use express-ipfilter

Installation

npm install express-ipfilter

Usage with Express

var express = require('express')
    , ipfilter = require('express-ipfilter')
    , app = express.createServer()
    ;

// Whitelist the following IPs 
var ips = ['127.0.0.1'];

// Create the server 
app.use(ipfilter(ips, {mode: 'allow'}));
app.listen(3000);

https://www.npmjs.com/package/express-ipfilter#installation

Boorish answered 23/6, 2016 at 8:48 Comment(0)
S
0

I had to tweak @Jilo-Paulose's solution a little bit in my case:

const express = require('express');
const ipfilter = require('express-ipfilter');

express()
    .use(ipfilter.IpFilter(['127.0.0.1','::1'], {'mode': 'allow'}))
    .use(express.static('static'))
    .listen(3000);
Skillful answered 4/3, 2023 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.