Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block public access to expressjs app

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

like image 200
CuriousMind Avatar asked Dec 26 '22 00:12

CuriousMind


1 Answers

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');
});
like image 190
edef Avatar answered Dec 31 '22 08:12

edef