简体   繁体   中英

how to get ip address inside cors Dynamic Origin?

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

I assume that you want to provide access based on the IP address of the user and not based on the domain name(ie 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.' })
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM