简体   繁体   English

适用于 Firebase 的 Cloud Functions 的安全 HTTP 触发器

[英]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?有没有办法在触发云功能之前检查用户是否获得了 firebase 授权? (Or within the function) (或在函数内)

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.您需要随请求一起发送 Firebase ID 令牌(例如在 AJAX 请求的Authorization标头中),然后使用 Firebase Admin SDK 对其进行验证。 There is an in-depth example in the Cloud Functions for Firebase samples repository. Cloud Functions for Firebase 示例存储库中有一个深入的示例 It looks something like this (made shorter for SO post):它看起来像这样(为 SO 帖子缩短了):

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

Since the question asks for auth-based access (1) within, or (2) before a function, here's an method for the "before" case: >由于该问题要求函数内或 (2) 内进行基于身份验证的访问 (1),因此这里是“之前”情况的一种方法:>

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.由于每个 Firebase 项目也是 Google Cloud 项目——并且GCP 允许“私有”功能,因此您可以在功能之外设置项目范围或每个功能的权限,以便只有经过身份验证的用户才能触发该功能.

Unauthorized users will be rejected before function invocation , even if they try to hit the endpoint.未经授权的用户将在函数调用之前被拒绝,即使他们试图点击端点。

Here's documentation on setting permissions andauthenticating users .这是有关设置权限验证用户的文档。 As of writing, I believe using this method requires users to have a Google account to authenticate.在撰写本文时,我认为使用此方法需要用户拥有 Google 帐户才能进行身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM