如何允许特定域访问云功能

问题描述 投票:3回答:1

我正在使用Firebase云功能,并且第一次看到cors然后将origin设置为true。但是通过这种方式,任何人都可以访问我的功能,因此我寻找了一种仅允许特定域访问我的云功能的方法,我从cors github页面获取了代码并进行了尝试,但是在等待之后,我意外关闭了连接。

这是我的函数index.js-

const functions = require('firebase-functions');
const cors = require('cors');

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (whitelist.indexOf(req.header('Origin')) !== -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
}

exports.api = functions.https.onRequest((req, res) => {
cors(req, res, () => {  
    var d = new Date();
   var n = d.getHours();
  if (n > 8 && n < 17) {
    res.status(200).send("Get started")
  } else {
    res.status(200).send("Closed")
  } 
})
});
javascript firebase google-cloud-functions
1个回答
0
投票

使用Firebase Cloud Functions上的HTTP触发功能,cors中间件origin参数将为undefined,请求标头Origin值为:

var whitelist = ['https://example1.com']
var corsOptions = {
  origin: function (origin, callback) {
    console.log(origin) // undefined
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  console.log(req.header('Origin')) // undefined
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})

除非您对函数进行请求时自行设置Origin标头。例如:

await http.get(
  'https://example1.com/yourfunction',
  headers: {
    "Origin": "https://example2.com",
  },
);

问题是任何人都可以编写上述请求(Origin标头可以伪造),因此,this post suggests一种更简单的方法来验证访问权限是通过发送诸如Firebase Auth生成的令牌之类的东西登录时(或者您可以向发送方提供他们需要发送的密钥):

await http.get(
  'https://example1.com/yourfunction',
  headers: {
    "Authorization": "Bearer your_api_token_here",
  },
);

然后您将在Cloud Function中使用verify that it's legit(而不是检查潜在的伪造来源)。

© www.soinside.com 2019 - 2024. All rights reserved.