Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure HTTP trigger for Cloud Functions for Firebase

Is there a way to check if a user is firebase-authorized before triggering a cloud function? (Or within the function)

like image 972
Geoffrey Burdett Avatar asked Apr 05 '17 18:04

Geoffrey Burdett


People also ask

Does Firebase use HTTP requests?

Requests on your Firebase Hosting site can be proxied to specific HTTP functions. This also allows you to use your own custom domain with an HTTP function.


2 Answers

Yes. You will need to send the Firebase ID token along with the request (for example in the Authorization header of an AJAX request), then verify it using the Firebase Admin SDK. There is an in-depth example in the Cloud Functions for Firebase samples repository. It looks something like this (made shorter for SO post):

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')();

const validateFirebaseIdToken = (req, res, next) => {
  cors(req, res, () => {
    const idToken = req.headers.authorization.split('Bearer ')[1];
    admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
      console.log('ID Token correctly decoded', decodedIdToken);
      req.user = decodedIdToken;
      next();
    }).catch(error => {
      console.error('Error while verifying Firebase ID token:', error);
      res.status(403).send('Unauthorized');
    });
  });
};

exports.myFn = functions.https.onRequest((req, res) => {
  validateFirebaseIdToken(req, res, () => {
    // now you know they're authorized and `req.user` has info about them
  });
});
like image 163
Michael Bleigh Avatar answered Sep 24 '22 15:09

Michael Bleigh


Since the question asks for auth-based access (1) within, or (2) before a function, here's an method for the "before" case: >

Since every Firebase Project is also a Google Cloud Project -- and GCP allows for "private" functions, you can set project-wide or per-function permissions outside the function(s), so that only authenticated users can cause the function to fire.

Unauthorized users will be rejected before function invocation, even if they try to hit the endpoint.

Here's documentation on setting permissions and authenticating users. As of writing, I believe using this method requires users to have a Google account to authenticate.

like image 41
ultraGentle Avatar answered Sep 23 '22 15:09

ultraGentle