I'm trying to use the code sample from here https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js but my cloud function keeps crashing saying
req.headers.split is not a function
at cors (/user_code/index.js:25:37)
at cors (/user_code/node_modules/cors/lib/index.js:188:7)
at /user_code/node_modules/cors/lib/index.js:224:17
at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
at /user_code/node_modules/cors/lib/index.js:219:13
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.savedProfiles.functions.https.onRequest (/user_code/index.js:14:5)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:41)
at /var/tmp/worker/worker.js:671:7
I'm not sure how else to get it to work. This is the code that I've used so far:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
exports.savedProfiles = functions.https.onRequest((req, res) => {
cors(req, res, () => {
if ((!req.headers.authorization || !req.headers.authorization.includes('Bearer '))) {
console.log(req.headers);
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.');
res.status(403).send('Unauthorized');
return;
}
const tokenId = req.headers.split('Bearer ')[2];
res.status(200).send('Testing');
return;
});
});
I understand that the error is due to req.headers.split('Bearer ')[2];
which simply gets the token from the header. But I think the problem is that req.headers can be a string
as well as a string[]
. How would I go about getting this to work? Thanks.
req.headers
is always an object indexed by the name of the header, never a string. The code you referred to is doing this instead:
req.headers.authorization.split('Bearer ')[1]
It's accessing the "Authorization" header, which is a string, then splitting it.