Cors Error Within A Cloud Function
I've copied exactly what's written in the sample code here: https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js but I keep gettin
Solution 1:
So I managed to get this to work without even using express. Here's what I came up with:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const cookieParser = require('cookie-parser')();
const cors = require('cors')({
origin: 'http://localhost:8100'
});
exports.savedProfiles = functions.https.onRequest((req, res) => {
cors(req, res, () => {
console.log('Check if request is authorized with Firebase ID token');
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
!req.cookies.__session) {
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.');
res.status(403).send('Unauthorized');
return;
}
let idToken;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
// Read the ID Token from the Authorization header.
idToken = req.headers.authorization.split('Bearer ')[1];
} else {
// Read the ID Token from cookie.
idToken = req.cookies.__session;
}
admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
req.user = decodedIdToken;
res.status(200).send("SUCCESS");
return;
}).catch((error) => {
console.error('Error while verifying Firebase ID token:', error);
res.status(403).send('Unauthorized');
});
});
});
Solution 2:
I did some test and on my PC the above cors setup works as expected.
Check the http response status: if I reproduce an error status (for example a 403) in my setup the Access-Control-Allow-Origin
header is not present.
In validateFirebaseIdToken
try to add:
res.set('Access-Control-Allow-Origin', '*');
just before res.status(403).send('Unauthorized');
expression to enable CORS also when errors happens.
Post a Comment for "Cors Error Within A Cloud Function"