I am using firebase cloud functions and at the first time I saw cors then set origin to true.. but in that way anyone can access to my functions, so I looked a way to allow only specific domains to access my cloud functions, I got the code from cors github page and tried it, but I get unexpectedly closed the connection after waiting and waiting.
here is my function 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")
}
})
});
With an HTTP triggered function on Firebase Cloud Functions the cors middleware origin
parameter will be undefined, as will be the request header Origin value:
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.'})
})
unless you set the Origin
header yourself when you make the request to the function. For example:
await http.get(
'https://example1.com/yourfunction',
headers: {
"Origin": "https://example2.com",
},
);
The problem is that anyone can write the above request (the Origin header can be faked), so as this post suggests a more fool-proof way to verify access is by sending something like the token that Firebase Auth generates when you sign in (or you can provide the sending party with a secret key they would need to send):
await http.get(
'https://example1.com/yourfunction',
headers: {
"Authorization": "Bearer your_api_token_here",
},
);
You would then verify that it's legit in the Cloud Function (instead of checking the potentially fake origin).
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