You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中Firebase Auth验证后调用Cloud Function仍报UNAUTHENTICATED错误

环境信息

  • Unity编辑器版本:2021.3.9f
  • Firebase Unity SDK版本:9.6.0
  • SDK安装来源:FirebaseFunctions(.unitypackage或Unity Package Manager)
  • 有问题的Firebase组件:FirebaseFunctions
  • 正在使用的其他Firebase组件:FirebaseFunctions、Auth
  • 额外使用的SDK:无
  • Unity编辑器运行平台:Windows
  • 目标平台:Android
  • 脚本运行时:IL2CPP

问题描述

已在Unity中集成Firebase Auth并功能正常,认证完成后调用Firebase Cloud Function时触发UNAUTHENTICATED异常。调用代码如下:

void FirebaseFucntionTest()
{
    var data = new Dictionary<string, object>();
    Debug.Log("Calling");
    FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
    Debug.Log(FirebaseAuth.DefaultInstance.CurrentUser.DisplayName);

    var function = functions.GetHttpsCallable("testunity");
    function.CallAsync(data).ContinueWith((task) =>
    {
       if (task.IsFaulted)
       {
           foreach (var inner in task.Exception.InnerExceptions)
           {
               if (inner is FunctionsException)
               {
                   var e = (FunctionsException)inner;
                   var code = e.ErrorCode;
                   var message = e.ToString();
                   Debug.Log(message);
                   Debug.Log(code);
               }
           }
       }
       else if (task.IsCompleted)
       {
           Debug.Log((string)task.Result.Data);
       }
    });
}

调用前能正常获取当前用户名,但函数调用报错:

Firebase.Functions.FunctionsException: UNAUTHENTICATED
at Firebase.Functions.HttpsCallableReference.b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00000] in <00000000000000000000000000000000>:0

解决方法

1. 配置Cloud Function的IAM权限

默认创建的Cloud Function未开放给认证用户访问,需修改权限:

  • 进入Firebase控制台「Cloud Functions」页面,找到testunity函数
  • 进入函数详情页的「权限」标签
  • 添加权限:成员选择所有已认证用户(allAuthenticatedUsers),角色设置为「Cloud Functions 调用者」

2. 在Cloud Function代码中验证身份

在函数逻辑里强制验证用户认证状态,示例Node.js代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.testunity = functions.https.onCall(async (data, context) => {
  // 拦截未认证请求
  if (!context.auth) {
    throw new functions.https.HttpsError('unauthenticated', '用户未完成认证');
  }
  // 业务逻辑代码
  return { message: "调用成功" };
});

3. 确保Unity中认证状态稳定

用户登录后Auth状态可能存在同步延迟,建议在Auth状态变更回调中确认登录完成后再调用函数:

void Start()
{
    FirebaseAuth.DefaultInstance.StateChanged += AuthStateChanged;
}

void AuthStateChanged(object sender, System.EventArgs e)
{
    var user = FirebaseAuth.DefaultInstance.CurrentUser;
    if (user != null)
    {
        // 确认用户已登录后执行函数调用
        FirebaseFucntionTest();
    }
}

4. 核对项目配置文件

确保Unity项目中的google-services.json与Cloud Function所属的Firebase项目完全匹配,避免跨项目配置导致的认证失败。

内容的提问来源于stack exchange,提问作者Indra Kumar Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:40:56