为什么我不能在Firebase Cloud Function中使用“allAuthenticatedUsers”?

5
使用 Firebase CLI 部署 Firebase 函数时,默认会将 Cloud Functions Invoker 权限授予 allUsers。在这种设置下,下面的代码可以正常运行。 Cloud Functions Invoker 权限也可以授予 allAuthenticatedUsers。但是,当我为 addMessage 实现此更改时,只会收到 UNAUTHENTICATED 的错误响应。
为什么 allAuthenticatedUsers 不能用于这个 Firebase 云函数?

注意: 这个问答是由Furkan Yurdakul发布的一个已被删除的问题引起的,涉及他的 Firebase 应用中 allAuthenticatedUsers 无法与 Firebase 可调用函数一起使用的原因。


基于文档的最小工作示例,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);
    }
  });
1个回答

13
简单来说,如果传递给云函数的ID令牌代表使用FirebaseGoogle本身通过Google登录的Google帐户,则可以工作,否则不行。
allAuthenticatedUsers视为allAuthenticatedGoogleUsers,而不是allAuthenticatedFirebaseUsers
背景信息
对于与Firebase客户端SDK一起使用的Callable Firebase Functions,通常会授予allUsers调用它的权限(默认设置Firebase CLI部署的函数)。
Google云函数的有效身份验证客户端请求必须具有Authorization:Bearer ID_TOKEN标头(首选)或?access_token=ID_TOKEN。这里,ID_TOKEN是已登录的Google用户的ID令牌,作为JWT
当Firebase客户端SDK调用可调用函数时,它们会为您设置当前用户的ID tokenAuthorization标头(如果用户已登录,在此处)。这样做是为了可以在onCall()函数的context参数中使用用户的身份验证令牌。但重要的是,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 Forbidden错误的补充说明

如果您的函数在部署后持续抛出403错误,那么很可能是因为您正在使用过时的Firebase CLI副本,正如文档所指出的那样:

注意:使用低于7.7.0版本的任何Firebase CLI部署的新HTTP和HTTP可调用函数默认为私有,并在调用时抛出HTTP 403错误。请明确使这些函数公开或者更新Firebase CLI,然后再部署任何新函数。


谢谢你的回答,它帮了我很大的忙!顺便说一下,您可能想使用“unauthenticated”作为HttpsError代码,因为它更能说明问题。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接