繁体   English   中英

如何在cors Dynamic Origin中获取IP地址?

[英]how to get ip address inside cors Dynamic Origin?

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

我假设您要基于用户的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.' })
})

根据Cors文件: https : //github.com/expressjs/cors#configuring-cors-asynchronouslyly

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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