【问题标题】:How can I retrieve the authentication data of a user when using a Firebase callable function?使用 Firebase 可调用函数时如何检索用户的身份验证数据?
【发布时间】:2020-10-04 10:08:15
【问题描述】:

我在 Flutter 中构建的移动应用程序使用 google 登录来注册用户。在这个应用程序中,我使用 Cloud Functions Plugin for Flutter 调用 Firebase 云函数(称为 questionAnswer)。

如果我从 this 文档中正确理解,https 请求应自动包含用户的 Firebase 身份验证。

如何从 Cloud Function 中检索用户的身份验证信息?我需要它来访问 Firebase 云数据库中与该特定用户关联的数据。我应该在 https 请求中包含谷歌身份验证令牌作为参数吗?

这是我在 Flutter 应用中的代码:

final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
      functionName: 'questionAnswer',
  );

 fetchHttps() async {
   dynamic resp = await callable.call();
   print(resp);
 }

这是云函数中的代码

exports.questionAnswer = functions.https.onCall(() => {
  console.log('addNumbersLog', "holaLog");
    return answer;
  });

【问题讨论】:

    标签: firebase flutter firebase-authentication google-cloud-functions


    【解决方案1】:

    documentation 中可以看出,auth 信息在传递给函数的第二个参数中。您需要声明并使用它:

    exports.questionAnswer = functions.https.onCall((data, context) => {
      console.log('addNumbersLog', "holaLog");
      console.log(context.auth);
      return answer;
    });
    

    context 这里是一个CallableContext 对象。

    【讨论】:

      【解决方案2】:

      您可以从CallableContext 参数中获取用户的uid,该参数作为第二个参数传递给您的onCall 处理程序。

      从那里您可以使用.getUser() 方法检索Firebase UserRecord 并传入uid

      exports.questionAnswer = functions.https.onCall((data, { auth }) => {
          admin.auth().getUser(auth.uid)
            .then((userRecord) => {
              // See the UserRecord reference doc for the contents of userRecord.
              console.log('Successfully fetched user data:', userRecord.toJSON());
            })
            .catch(function(error) {
              console.log('Error fetching user data:', error);
            });
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 2020-04-25
        • 2018-01-27
        • 1970-01-01
        • 2020-08-20
        • 2017-01-29
        • 2020-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多