Search code examples
node.jsexpresswhitelistwebsecurity

Is it safe to whitelist an IP address using req.ip in express, node.js?


I want to whitelist access to a section of my website to only work for requests coming from a specific IP address. Is it safe to filter by IP address using req.ip? Is there an alternate best practice for things like this?

Example:

const express = require("express");

const app = express();

app.use((req, res, next) => {
  if (req.ip !== "x.x.x.x") {
    return res.status(403).send();
  }
  next();
});

app.get("/whitelist", (req, res, next) => {
  res.send("content");
});

app.listen(3000, "localhost", () => {
  console.log("Server is up");
});

Solution

  • No, this is not enough. The IP of the request can be faked. If someone gets ahold of your source code, and if they cared enough, they'll be able to access the restricted route.

    Require a password (or some way of authenticating) instead.