首页 > 解决方案 > 如何在 cors Dynamic Origin 中获取 IP 地址?

问题描述

我用nodejs构建restAPI,我想限制用户访问白名单的ip或域,为此我使用NPM的CORS包,但我无法获取访问restAPI的客户端IP地址,所以..如何获取IP地址?

这里的代码:

const whitelist = ['http://localhost', 'http://127.0.0.1']
const corsOptions = {
  origin: function (origin, callback) {
    console.log(whitelist.indexOf(origin))
    console.log(origin)
    // if (whitelist.indexOf(origin) !== -1) {
      if (whitelist.indexOf('127.0.0.1') !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error('Your ip address is not whitelisted'))
    }
  },
  methods: ["GET", "PUT", "POST", "DELETE", "HEAD", "PATCH"],
  allowedHeaders: ["Content-Type", "Authorization"],
  credentials: true
}
app.get('/v2/cors', Cors(corsOptions), (req, res) => {
    res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' })
})

标签: node.jscors

解决方案


我假设您希望基于用户的 IP 地址而不是基于域名(即来源)提供访问权限。在包的文档中,他们提到为此使用 corsOptionsDelegate。尝试这个...

const whitelist = ['http://localhost', 'http://127.0.0.1']
var corsOptionsDelegate = function (req, callback) {
  const corsOptions = {
      methods: ["GET", "PUT", "POST", "DELETE", "HEAD", "PATCH"],
      allowedHeaders: ["Content-Type", "Authorization"],
      credentials: true
  };

  const myIpAddress = req.connection.remoteAddress; // This is where you get the IP address from the request
  if (whitelist.indexOf(myIpAddress) !== -1) {
      corsOptions.origin = true
  } else {
      corsOptions.origin = false
  }
  callback(null, corsOptions);
}

app.get('/v2/cors', Cors(corsOptionsDelegate), (req, res) => {
  res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' })
})

推荐阅读