Functions-samples: Issues with Access-Control-Allow-Origin

Created on 14 Mar 2017  Â·  13Comments  Â·  Source: firebase/functions-samples

I'm having issues with Access-Control-Allow-Origin in combination with Firebase Cloud Functions.

I followed the examples to protect my https endpoints to make sure that only users with a valid token can access certain eindpoints.

I configured cors en imported the cors module. The strange thing is that I encounter completely random origin errors. Sometimes the request is valid and other times the request is invalid.

Error
group

For reference and debugging, here are my cloud functions.

const cors = require('cors')({ origin: true });

const validateFirebaseIdToken = (async (req, res, next) => {
  cors(req, res, async () => {
    const authorization = req.headers.authorization;
    let decodedToken;
    if (!authorization) {
      res.status(403).send('No token Provided');
      return;
    }
    try {
      decodedToken = await admin.auth().verifyIdToken(authorization);
      req.user = decodedToken;
      next();
    } catch (error) {
      res.status(403).send('Token is invalid Provided');
      return;
    }
  });
});

const findUserByEmail = (async (req, res, next) => {
  const emailAddress = req.body.emailAddress;
  let userRecord;
  if (!emailAddress) {
    res.status(403).send('No email address provided');
    return;
  }
  try {
    userRecord = await admin.auth().getUserByEmail(emailAddress);
    req.userRecord = userRecord.toJSON();
    next();
  } catch (error) {
    if (error.code === 'auth/user-not-found') {
      next();
    }
    res.status(403).send('Something went wrong', error);
    return;
  }
});

exports.createToken = functions.https.onRequest(async (req: any, res: any) => {
  validateFirebaseIdToken(req, res, async () => {
    const organizationUID = req.body.organizationUID;
    let newToken;

    if (!organizationUID) {
      res.status(403).send('No organizationUID Provided');
      return;
    }

    const additionalClaims = {
      organizationUID
    };

    try {
      newToken = await admin.auth().createCustomToken(req.user.uid, additionalClaims);
    } catch (error) {
      res.status(403).send('Error creating a new token');
      console.log('error', error);
    }
    res.status(200).send({ token: newToken });
  });
});

exports.returnUser = functions.https.onRequest(async (req: any, res: any) => {
  validateFirebaseIdToken(req, res, async () => {
    findUserByEmail(req, res, async () => {

      if (req.userRecord) {
        const user = {
          uid: req.userRecord.uid,
          newUser: false
        };
        res.status(200).json(user);
        return;
      }
      let userRecord;
      const randomPassword = Math.random().toString(36).slice(-12);
      const newUser = {
        email: req.body.emailAddress,
        emailVerified: false,
        password: randomPassword
      };
      try {
        userRecord = await admin.auth().createUser(newUser);
        req.userRecord = userRecord.toJSON();

        const user = {
          uid: req.userRecord.uid,
          newUser: true
        };
        res.status(200).json(user);
        return;
      } catch (error) {
        res.status(403).send('Can\'t generate new user');
      }
    });
  });
});

Most helpful comment

I have the same problem. Can someone help?

All 13 comments

It seems there is a 500 error returned. Can you check the Function log (in the Firebase console) to see if there is more info about these 500 errors? in case that helps...

Hi Frank, This doesn't look like an issue with the firebase-samples repo. Would you mind putting this question on Stack Overflow or reaching out to support? ☼, Kato

is cors module necessary ?

I have the same problem. Can someone help?

hi did you resolve this issue?
I am also having the same issue

I am having the same issue as well. How did you resolve the problem?

it was a cors issue.

const cors = require('cors');
const corsOptions = {
origin: '*',
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'],
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};

app.use(cors(corsOptions));
app.get('/portfolio', cors(corsOptions), (() => {
// rest of the code here.
}

Thank you for this. Do I put this around every function in my .js file that needs access to the firebase DB?

On 19 Mar 2018, at 14:58, Yacine Soufiane <[email protected]notifications@github.com> wrote:

it was a cors issue.

const cors = require('cors');
const corsOptions = {
origin: '*',
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'],
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};

app.use(cors(corsOptions));
app.get('/portfolio', cors(corsOptions), (() => {
// rest of the code here.
}

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://github.com/firebase/functions-samples/issues/44#issuecomment-374220588, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AfSilUps5bCbokMrWs8A-cfdyvSX1gRTks5tf7l6gaJpZM4MdGl2.

I am not sure what you are trying to do but I believe the code I pasted will allow you to call methods on the Express application regardless of what the app/function does (access DB or not).

cors(req, res, async () => {

passing async function to third parameter of cors does not work because it does not return the promise object.

https://github.com/expressjs/cors/blob/master/lib/index.js#L188

It may cause the problem.

I have the same problem. Can someone help?
how to solve this

hi did you resolve this issue?
I am also having the same issue

hii if your issue resolve please let me know..

I also Face the same issue , so till now did any one resolved this issue .?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nhathiwala picture nhathiwala  Â·  4Comments

beratuslu picture beratuslu  Â·  4Comments

artcab picture artcab  Â·  4Comments

palimad picture palimad  Â·  3Comments

tsaarikivi picture tsaarikivi  Â·  4Comments