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

时间:2017-06-22 12:47:29

标签: javascript firebase google-cloud-functions

我正在使用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")
  } 
})
});

1 个答案:

答案 0 :(得分:0)

在Firebase Cloud Functions上使用HTTP触发功能时,cors中间件origin参数将未定义,请求标头 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",
  },
);

然后,您将在云功能中verify that it's legit(而不是检查潜在的虚假来源)。

相关问题