在 express、node.js 中使用 req.ip 将 IP 地址列入白名单是否安全?

问题描述

我想将我网站的某个部分的访问权限列入白名单,以便仅适用于来自特定 IP 地址的请求。使用 req.ip 按 IP 地址过滤是否安全?对于此类事情,是否有替代的最佳做法?

示例:

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,next) => {
  res.send("content");
});

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

解决方法

不,这还不够。 The IP of the request can be faked。如果有人知道您的源代码,并且如果他们足够关心,他们将能够访问受限路径。

需要密码(或某种身份验证方式)。