question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issues with Access-Control-Allow-Origin

See original GitHub issue

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');
      }
    });
  });
});

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:13 (3 by maintainers)

github_iconTop GitHub Comments

17reactions
kartikgreencommented, Sep 14, 2017

I have the same problem. Can someone help?

2reactions
kubooncommented, Dec 26, 2018

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

What security risks exist when setting Access-Control-Allow ...
By responding with Access-Control-Allow-Origin: * , the requested resource allows sharing with every origin. This basically means that any ...
Read more >
Is Access-Control-Allow-Origin: * insecure?
The Access-Control-Allow-Origin specifies the allowed origin that can make cross-origin requests. The special value * means “all origins” which ...
Read more >
Access-Control-Allow-Origin - HTTP - MDN Web Docs - Mozilla
The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.
Read more >
3 Ways to Fix the CORS Error — and How the Access-Control ...
Fix one: install the Allow-Control-Allow-Origin plugin. The quickest fix you can make is to install the moesif CORS extension .
Read more >
CORS and the Access-Control-Allow-Origin response header
The Access-Control-Allow-Origin header is included in the response from one website to a request originating from another website, and identifies the permitted ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found