4

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

NeXtMaN_786
  • 661
  • 2
  • 12
  • 23
  • Check using onCall as explained here https://stackoverflow.com/questions/51066434/firebase-cloud-functions-difference-between-onrequest-and-oncall?noredirect=1&lq=1 – cbeltrangomez May 07 '20 at 06:48

1 Answers1

-1

You need to add cors before the initialize function AND in your express function

'use strict';

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors';
import * as express from 'express';

cors({
  origin: true,
}); // << for bootstrap 
admin.initializeApp(functions.config().firebase);

const app = express();
app.use(cors()); // << for what you just defined

This should work fine

Pian0_M4n
  • 2,505
  • 31
  • 35