问题
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