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(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.' })
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With