Secure HTTP trigger for Cloud Functions for Firebase

别说谁变了你拦得住时间么 提交于 2019-12-28 05:42:04

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/43238611/secure-http-trigger-for-cloud-functions-for-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!