Cloud Functions for Firebase 的安全 HTTP 触发器 [英] Secure HTTP trigger for Cloud Functions for Firebase

查看:21
本文介绍了Cloud Functions for Firebase 的安全 HTTP 触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在触发云功能之前检查用户是否获得了 Firebase 授权?(或函数内)

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

推荐答案

是的.您需要将 Firebase ID 令牌与请求一起发送(例如在 AJAX 请求的 Authorization 标头中),然后使用 Firebase Admin SDK 对其进行验证.云中有一个深入示例Firebase 示例存储库的函数.它看起来像这样(SO 帖子更短):

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

这篇关于Cloud Functions for Firebase 的安全 HTTP 触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆