我用nodejs构建restAPI,我想用白名单的IP或域来限制用户访问权限,为此我使用NPM's CORS package,但是我无法获得访问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.' })
})
答案 0 :(得分:1)
我假设您要基于用户的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.' })
})
答案 1 :(得分:0)
根据Cors文档: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.' })
})