首页 > 解决方案 > Firebase 云功能在登录后立即返回未经身份验证

问题描述

我有以下问题。我已经实现了一个 Firebase 云函数,它从 Firestore 返回用户配置文件。我的云功能要求您登录到 Firebase 才能查询它们。

现在,在我的应用程序中,我在FirebaseAuth.instance.onAuthStateChanged云功能上实现了该功能,以获取用户个人资料。但是,当我登录到应用程序时,触发的调用返回 PlatformException,原因为 UNAUTHENTICATED,尽管在此之前的一行中,我检查了当前用户FirebaseAuth.instance.currentUser()并获得了正确且有效的 uid。Firebase 中没有涉及此函数的日志,仅针对所有成功且也被调用的其他函数FirebaseAuth.instance.onAuthStateChanged

这是云功能,基本上非常简单:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

export default functions.https.onCall(async (data, context) => {
  console.info(`[api-userProfile] called with userUid=${data.userUid}`);

  const user: FirebaseFirestore.QuerySnapshot = await admin
    .firestore()
    .collection("userProfiles")
    .where("userUid", "==", data.userUid)
    .get();

  if (user.docs.length === 1) {
    console.info(
      `[api-userProfile] returning user for userUid=${data.userUid}`
    );
    return user.docs[0].data();
  }

  console.info(`[api-userProfile] could not find userUid=${data.userUid}`);
  return null;
});

这就是我所说的:

final _disposeBag = CompositeSubscription();
  final userProfile = BehaviorSubject<UserProfile>();

final _userProfilesFn =
      CloudFunctions.instance.getHttpsCallable(functionName: "api-userProfile");

UserProfileStore() {
  _disposeBag.add(FirebaseAuth.instance.onAuthStateChanged
      .map((v) => v != null ? v : throw "")
      .handleError((v) => userProfile.add(null))
      .asyncMap((v) {
        print(v.uid); // here the correct uid is printed
        return _userProfilesFn.call({"userUid": v.uid});
      })
      .map((v) => v as Map)
      .map((v) => UserProfile.fromJson(v))
      .addTo(userProfile)
      .listen((_) {}));
}

抛出的错误是(第一行是登录用户的 uid):

I/flutter ( 9370): DXrcqtU34Dh8UfZYnsNdxn31hqx2
E/flutter ( 9370): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(functionsError, Cloud function failed with exception., {code: UNAUTHENTICATED, details: null, message: UNAUTHENTICATED})
E/flutter ( 9370): #0      StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:569
E/flutter ( 9370): #1      MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:321
E/flutter ( 9370): <asynchronous suspension>
E/flutter ( 9370): #2      MethodChannelCloudFunctions.callCloudFunction 
package:cloud_functions_platform_interface/src/method_channel_cloud_functions.dart:43
E/flutter ( 9370): #3      HttpsCallable.call 
package:cloud_functions/src/https_callable.dart:33
E/flutter ( 9370): #4      new UserProfileStore.<anonymous closure> 

标签: firebaseflutterdartgoogle-cloud-firestoregoogle-cloud-functions

解决方案


我认为您应该使用命名导出,如下所示:

export const api_userProfile = functions.https.onCall(async (data, context) => {...});

然后您可以使用该名称调用 CF。


推荐阅读