为什么我在尝试执行 HttpsCallable 函数时不断收到 Unhandled Exception: [firebase_functions/unauthenticated] UNAUTHENTICATED 错误

问题描述 投票:0回答:1

我不断收到以下错误。我以用户身份登录我的应用程序并使用 Firebase 身份验证。我登录的用户帐户是唯一的用户,并且具有所有者、Cloud Functions 管理员、Cloud Functions Invoker、Cloud Run 管理员、Cloud Run Invoker 和 Firebase 管理员角色。我认为我不需要所有这些角色,我只是在尽我所能来解决身份验证错误。


代码:

Future<void> helloWorldTest() async {
  HttpsCallable callableHW =
      FirebaseFunctions.instance.httpsCallable('helloWorld');
  final results = await callableHW.call();
  print('results are $results'); // Print the request data
}


const admin = require("firebase-admin");
const {onCall, HttpsError} = require("firebase-functions/v2/https");
admin.initializeApp();

exports.helloWorld = onCall(async (request) => {
  return "Hello World";
});`

错误:

E/flutter(22286):[错误:flutter/runtime/dart_vm_initializer.cc(41)]>未处理的异常:[firebase_functions/未经身份验证]>未经身份验证

我尝试使用 Flutter 应用程序中的 HttpsCallable 来调用 onCall >Firebase Cloud Function,但不断收到以下错误。

[firebase_functions/未经身份验证] 未经身份验证

flutter firebase firebase-authentication google-cloud-functions
1个回答
0
投票

该问题可能是因为您需要使用身份验证令牌初始化 Firebase Functions 实例。以下是修复方法:

Future<void> helloWorldTest() async {
  // Get the current user
  final user = FirebaseAuth.instance.currentUser;
  
  if (user != null) {
    // Get the ID token
    final idToken = await user.getIdToken();
    
    // Create the callable function with auth
    final callable = FirebaseFunctions.instance
        .httpsCallable('helloWorld');
    
    try {
      final result = await callable.call();
      print('Result: ${result.data}');
    } catch (e) {
      print('Error: $e');
    }
  }
}

还要确保:

  1. 您已在 main.dart 中正确初始化 Firebase:

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

  1. 您的 Firebase 规则允许函数调用

  2. 用户在拨打电话之前实际上已经经过身份验证

© www.soinside.com 2019 - 2024. All rights reserved.