I have a simple firebase setup and an ionic application. I've been trying for a few days to get cloud functions to work. But this error doesn't seem to go away:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-my-app.cloudfunctions.net/savedProfiles. (Reason: CORS preflight channel did not succeed).
From the front end I have this:
let token = this.auth.user.getIdToken();
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Accept':'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}` })
};
this.httpClient.get('https://us-central1-my-app.cloudfunctions.net/savedProfiles', httpOptions)
.subscribe(data => {
console.log(data);
});
and my cloud function looks like this:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({
origin: true,
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'],
methods: ['OPTIONS', 'GET', 'PUT', 'POST', 'DELETE']
});
const app = express();
// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const validateFirebaseIdToken = (req, res, next) => {
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.',
'Make sure you authorize your request by providing the following HTTP header:',
'Authorization: Bearer <Firebase ID Token>',
'or by passing a "__session" cookie.');
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
.status(403).send('Unauthorized');
return;
}
let idToken;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
console.log('Found "Authorization" header');
// Read the ID Token from the Authorization header.
idToken = req.headers.authorization.split('Bearer ')[1];
} else {
console.log('Found "__session" cookie');
// Read the ID Token from cookie.
idToken = req.cookies.__session;
}
admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
console.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
return next();
}).catch((error) => {
console.error('Error while verifying Firebase ID token:', error);
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
.status(403)
.send('Unauthorized');
});
};
app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/savedProfiles', (req, res) => {
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
.send(`Hello ${req.user.name}`);
});
// This HTTPS endpoint can only be accessed by your Firebase Users.
// Requests need to be authorized by providing an `Authorization` HTTP header
// with value `Bearer <Firebase ID Token>`.
exports.savedProfiles = functions.https.onRequest(app);
This is similar to the sample code over here: https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint
I'm sure the solution is simple but I can't seem to understand what's going on. I thought app.use(cors);
was supposed to sort these sorts of issues out? If I don't add res.set('Access-Control-Allow-Origin', '*')
then I get a
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-my-app.cloudfunctions.net/savedProfiles. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
error. The errors that are returned to my console from the console log is this:
error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
headers: Object { normalizedNames: Map, lazyUpdate: null, headers: Map }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
If you would like me to expand the error let me know. Thanks