[英]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.