android - I get a error in Firebase functions Unauthenticated - Stack Overflow

I have a flutter app and now i need to accept payments in my app and i want to check if the payment is

I have a flutter app and now i need to accept payments in my app and i want to check if the payment is made by using firebase functions, but i constantly get the error unauthenticated.

I have added app check because that was necessary to implement the payment function i want. I get in appcheck that my request are verified, so i don't think that that is the problem. But if i call the function I get a error [firebase_functions/unauthenticated} UNAUTHENTICATED. I have changed the whole function just to test but I still get the same error:

Index.js

const admin = require("firebase-admin");

admin.initializeApp();

exports.testFunction = functions.https.onCall((data, context) => {
  console.log("Auth context:", context.auth);
  console.log("App Check token:", context.app);

  // Check if the user is authenticated
  if (!context.auth) {
    console.error("User is not authenticated.");
    throw new functions.https.HttpsError(
        "failed-precondition",
        "The function must be called while authenticated.",
    );
  }

  // Check if App Check is enabled and working
  if (!context.app) {
    console.error("App Check token is missing or invalid.");
    throw new functions.https.HttpsError(
        "failed-precondition",
        "App Check is not verified or missing.",
    );
  }

  // Return a simple success message
  return {message: "Authentication and App Check are working!"};
});

And this is my flutter screen where i test the firebase function:

import 'package:flutter/material.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_auth/firebase_auth.dart';

class TestFunctionScreen extends StatefulWidget {
  @override
  _TestFunctionScreenState createState() => _TestFunctionScreenState();
}

class _TestFunctionScreenState extends State<TestFunctionScreen> {
  String _result = "Press the button to test Firebase Function";

  Future<void> testFunction() async {
    try {
      // Ensure the user is logged in
      User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        setState(() {
          _result = "User not logged in. Please log in and try again.";
        });
        return;
      }
      print("Authenticated user: ${user.uid}");

      // Call Firebase Function
      final HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('testFunction');
      final response = await callable.call();
      setState(() {
        _result = "Function Response: ${response.data}";
      });
    } catch (e, stackTrace) {
      print("Error calling function: $e");
      print(stackTrace);
      setState(() {
        _result = "Error: $e";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test Firebase Function"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _result,
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: testFunction,
              child: Text("Test Firebase Function"),
            ),
          ],
        ),
      ),
    );
  }
}

This is the log of when I start the app up, until I press the test firebase functions button.

I/flutter (12954): App Check Token: eyJraWQiOiJRNmZ5eEEiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxOjQyMDMzMzQ2Mzk0MDphbmRyb2lkOmJlZDJmYjBiODkjE3MzE5NDQ4NDcsImp0aSI6InlwR0o5Q2g2YndpRDllbnNNN3VhYzVZQ0JtWDFXVWVuR1dQUkVIQW5YZzgifQ.VVQkV5d8GzU0KMMXe-JLE0Zkrg3809HCIbBOEf0oqJE7JFRyN6xJYMuOzez9Y1YR-aVbUtVUO7qcMg122znB9LFyd1kYZD-nx1N4umICG83DL12SUI9NWVYYv64L5qtbOZsP3eYW9ytqH8stHKka0bfe1y_eB2v7RzgNeSSpBuylRQHDJHkI2FEWr69PnE8WP6nD7K4cEZaQBR5VZPHH51aWkoj-VlODEdJBqMQXM6CdbQ1ZHDEjZvOucLUQlcbq11dsr4wvnO68SaILiq_rapIzvZCo7FltLhYJzGzjl4BBz6wM6YSQzbhA198_L0PS46tWFJ8MIPCedqWe434EAh_mX8FJcGlA5PdrdHJkxCcFB6oPbjViBldbsrSlEjNbQX1OFeBShv5PAumbj2EYbPt_1ensR0hvkaNw2oNwPS_4TyavizRhN_Vcg
I/flutter (12954): Authenticated user: 6hxNET0B1cbZ9hLMVk6p13
W/s.homes_captain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (unsupported,core-platform-api, reflection, allowed)
W/stain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (unsupported,core-platform-api, reflection, allowed)
W/s.tain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (unsupported,core-platform-api, reflection, allowed)
I/flutter (12954): Error calling function: [firebase_functions/unauthenticated] UNAUTHENTICATED
I/flutter (12954): 
I/flutter (12954): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:648:7)
I/flutter (12954): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:22:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:49:37)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #4      _TestFunctionScreenState.testFunction (package:homes_captain/paymentscreen.dart:27:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:648:7)
I/flutter (12954): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:22:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:49:37)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #4      _TestFunctionScreenState.testFunction (package:homes_captain/paymentscreen.dart:27:24)
I/flutter (12954): <asynchronous suspension>

I have a flutter app and now i need to accept payments in my app and i want to check if the payment is made by using firebase functions, but i constantly get the error unauthenticated.

I have added app check because that was necessary to implement the payment function i want. I get in appcheck that my request are verified, so i don't think that that is the problem. But if i call the function I get a error [firebase_functions/unauthenticated} UNAUTHENTICATED. I have changed the whole function just to test but I still get the same error:

Index.js

const admin = require("firebase-admin");

admin.initializeApp();

exports.testFunction = functions.https.onCall((data, context) => {
  console.log("Auth context:", context.auth);
  console.log("App Check token:", context.app);

  // Check if the user is authenticated
  if (!context.auth) {
    console.error("User is not authenticated.");
    throw new functions.https.HttpsError(
        "failed-precondition",
        "The function must be called while authenticated.",
    );
  }

  // Check if App Check is enabled and working
  if (!context.app) {
    console.error("App Check token is missing or invalid.");
    throw new functions.https.HttpsError(
        "failed-precondition",
        "App Check is not verified or missing.",
    );
  }

  // Return a simple success message
  return {message: "Authentication and App Check are working!"};
});

And this is my flutter screen where i test the firebase function:

import 'package:flutter/material.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_auth/firebase_auth.dart';

class TestFunctionScreen extends StatefulWidget {
  @override
  _TestFunctionScreenState createState() => _TestFunctionScreenState();
}

class _TestFunctionScreenState extends State<TestFunctionScreen> {
  String _result = "Press the button to test Firebase Function";

  Future<void> testFunction() async {
    try {
      // Ensure the user is logged in
      User? user = FirebaseAuth.instance.currentUser;
      if (user == null) {
        setState(() {
          _result = "User not logged in. Please log in and try again.";
        });
        return;
      }
      print("Authenticated user: ${user.uid}");

      // Call Firebase Function
      final HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('testFunction');
      final response = await callable.call();
      setState(() {
        _result = "Function Response: ${response.data}";
      });
    } catch (e, stackTrace) {
      print("Error calling function: $e");
      print(stackTrace);
      setState(() {
        _result = "Error: $e";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test Firebase Function"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _result,
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: testFunction,
              child: Text("Test Firebase Function"),
            ),
          ],
        ),
      ),
    );
  }
}

This is the log of when I start the app up, until I press the test firebase functions button.

I/flutter (12954): App Check Token: eyJraWQiOiJRNmZ5eEEiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxOjQyMDMzMzQ2Mzk0MDphbmRyb2lkOmJlZDJmYjBiODkjE3MzE5NDQ4NDcsImp0aSI6InlwR0o5Q2g2YndpRDllbnNNN3VhYzVZQ0JtWDFXVWVuR1dQUkVIQW5YZzgifQ.VVQkV5d8GzU0KMMXe-JLE0Zkrg3809HCIbBOEf0oqJE7JFRyN6xJYMuOzez9Y1YR-aVbUtVUO7qcMg122znB9LFyd1kYZD-nx1N4umICG83DL12SUI9NWVYYv64L5qtbOZsP3eYW9ytqH8stHKka0bfe1y_eB2v7RzgNeSSpBuylRQHDJHkI2FEWr69PnE8WP6nD7K4cEZaQBR5VZPHH51aWkoj-VlODEdJBqMQXM6CdbQ1ZHDEjZvOucLUQlcbq11dsr4wvnO68SaILiq_rapIzvZCo7FltLhYJzGzjl4BBz6wM6YSQzbhA198_L0PS46tWFJ8MIPCedqWe434EAh_mX8FJcGlA5PdrdHJkxCcFB6oPbjViBldbsrSlEjNbQX1OFeBShv5PAumbj2EYbPt_1ensR0hvkaNw2oNwPS_4TyavizRhN_Vcg
I/flutter (12954): Authenticated user: 6hxNET0B1cbZ9hLMVk6p13
W/s.homes_captain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (unsupported,core-platform-api, reflection, allowed)
W/stain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (unsupported,core-platform-api, reflection, allowed)
W/s.tain(12954): Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (unsupported,core-platform-api, reflection, allowed)
I/flutter (12954): Error calling function: [firebase_functions/unauthenticated] UNAUTHENTICATED
I/flutter (12954): 
I/flutter (12954): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:648:7)
I/flutter (12954): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:22:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:49:37)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #4      _TestFunctionScreenState.testFunction (package:homes_captain/paymentscreen.dart:27:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:648:7)
I/flutter (12954): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #2      MethodChannelHttpsCallable.call (package:cloud_functions_platform_interface/src/method_channel/method_channel_https_callable.dart:22:24)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #3      HttpsCallable.call (package:cloud_functions/src/https_callable.dart:49:37)
I/flutter (12954): <asynchronous suspension>
I/flutter (12954): #4      _TestFunctionScreenState.testFunction (package:homes_captain/paymentscreen.dart:27:24)
I/flutter (12954): <asynchronous suspension>
Share Improve this question asked Nov 18, 2024 at 15:51 Android_devNLAndroid_devNL 1471 silver badge16 bronze badges 1
  • firebase_functions/unauthenticated is throwing before even reaching your function, so it's the invoker user's permissions missing, not your end user's. Consider that an onCall deployment from firebase cli tries to set invoke permissions to allUsers, which may fail to be set if your deploying user doesn't have privileges enough, but the function will be deployed anyway. Maybe that's the permission you're missing on the function. You can also go to console.cloud.google/functions/list select the function, then Permissions, and a side panel will show more info and suggestions – maganap Commented Nov 23, 2024 at 13:04
Add a comment  | 

1 Answer 1

Reset to default 0

You either need to enable app-check on the client-side - or disable it on the cloud function side.

Either change:

exports.testFunction = functions.https.onCall((data, context) => {

To:

exports.testFunction = functions.https.onCall({ enforceAppCheck: false }, async (request) => {

Or pass something alike this as second argument of .getHttpsCallable(name, options):

HttpsCallableOptions.Builder().setLimitedUseAppCheckTokens(true).build()

HttpsCallableOptions least exists in Kotlin, unsure about the Dart syntax.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745610194a4635903.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信