首页 > 解决方案 > 为什么我的 Firebase 云函数不能使用 `allAuthenticatedUsers`?

问题描述

使用Firebase CLI部署 Firebase Functions 时,它们被配置为授予Cloud Functions Invoker权限allUsers。通过这样的设置,下面的代码可以按预期运行。

Cloud Functions InvokerallAuthenticatedUsers权限也可以授予. 但是,当我为 实现此更改时addMessage,我只会UNAUTHENTICATED使用下面的代码得到错误响应。

为什么不allAuthenticatedUsers适用于此 Firebase 云功能?


注意:此问答是由Furkan Yurdakul发布的一个现已删除的问题的结果,该问题是关于为什么allAuthenticatedUsers没有为他的 Firebase 应用程序使用他的 Firebase 可调用函数


MWE 基于文档,在此处addMessage定义:

firebase.auth().signInAnonymously() // for the sake of the MWE, this will normally be Facebook, Google, etc
  .then((credential) => {
    // logged in successfully, call my function
    const addMessage = firebase.functions().httpsCallable('addMessage');
    return addMessage({ text: messageText });
  })
  .then((result) => {
    // Read result of the Cloud Function.
    const sanitizedMessage = result.data.text;
    alert('The sanitized message is: ' + sanitizedMessage);
  })
  .catch((error) => {
    // something went wrong, keeping it simple for the MWE
    const errorCode = error.code;
    const errorMessage = error.message;

    if (errorCode === 'auth/operation-not-allowed') {
      alert('You must enable Anonymous auth in the Firebase Console.');
    } else {
      console.error(error);
    }
  });

标签: javascriptfirebasefirebase-authenticationgoogle-cloud-functions

解决方案


简而言之,如果传递给 Cloud Function 的 ID 令牌代表一个 Google 帐户(通过FirebaseGoogle 本身使用 Google 登录),它就可以工作,否则就不行。

认为allAuthenticatedUsersallAuthenticatedGoogleUsers不是allAuthenticatedFirebaseUsers.

背景资料

对于与 Firebase 客户端 SDK 一起使用的可调用 Firebase 函数,您通常会授予allUsers调用它的权限(默认设置Firebase CLI部署的函数)。

针对 Google Cloud Functions 的经过身份验证的有效客户端请求必须具有Authorization: Bearer ID_TOKEN标头(首选)或?access_token=ID_TOKEN. 这里,ID_TOKEN是作为JWT登录的 Google 用户的 ID 令牌。

当 Firebase 客户端 SDK 调用 Callable Function 时,它们Authorization会使用当前用户的ID 令牌为您设置标头(如果用户已登录,请点击此处)。这样做是为了可以在函数context参数中使用用户的身份验证令牌onCall()。但重要的是,Firebase 用户的 ID 令牌并不总是代表 Google 用户,这使其与allAuthenticatedUsers.

正因为如此,您必须通过检查代码中的可调用函数context.auth及其属性,如下所示。

export const addMessage = functions.https.onCall((data, context) => {
  if (!context.auth) {
    // Throwing a HttpsError so that the client gets the error details.
    throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called while authenticated.'
    );
  }

  // a valid user is logged in

  // do work
});

关于 403 禁止错误的附录

如果您的函数在部署后一直抛出 403 错误,这可能是因为您使用的是 Firebase CLI 的过时副本,如文档中突出显示的那样:

警告:使用低于 7.7.0 版本的任何 Firebase CLI 部署的新 HTTP 和 HTTP 可调用函数默认为私有,并在调用时引发 HTTP 403 错误。在部署任何新功能之前,明确公开这些功能更新您的 Firebase CLI 。


推荐阅读