how to get ip address inside cors Dynamic Origin?

谁说我不能喝 提交于 2021-02-10 14:17:46

问题


I build restAPI with nodejs and I want to limit user access with whitelisted ip or domain, to do that I use NPM's CORS package, but I cant get client ip address that access restAPI, so.. how to get the ip address?

here the code:

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.' })
})

回答1:


I assume that you want to provide access based on the IP address of the user and not based on the domain name(i.e origin). In the documentation of the package, they have mentioned using corsOptionsDelegate for this. Try this...

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.' })
})



回答2:


According to Cors document: https://github.com/expressjs/cors#configuring-cors-asynchronously

const whitelist = ['https://domain1.com', 'https://domain2.com']
const whitelistIp = ["116.208.110.107"];

const corsOptionsDelegate = function (req, callback) {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

let corsOptions;

if (whitelist.indexOf(req.header('Origin')) !== -1 || whitelistIp.indexOf(ip) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
    corsOptions = { origin: false } // disable CORS for this request
}
    callback(null, corsOptions) // callback expects two parameters: error and options
}

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


来源:https://stackoverflow.com/questions/51354948/how-to-get-ip-address-inside-cors-dynamic-origin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!