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

Flutter Web中FirebaseAuth getRedirectResult始终返回null致无限登录循环

Flutter Web FirebaseAuth重定向结果null导致无限登录循环的解决方案

问题根源分析

从控制台输出的GET https://p...79.firebaseapp.com/__/firebase/init.json 404 (Not Found)可确定核心问题:Firebase Auth处理重定向时无法加载必要配置文件,导致认证流程中断,最终getRedirectResult()返回null,触发无限登录循环。

解决方案步骤

1. 修正Firebase配置中的authDomain

你的authDomain设置为private.pages.dev,但重定向流程实际指向Firebase默认域名p...79.firebaseapp.com。需将authDomain改为Firebase项目的默认域名(格式为[你的projectId].firebaseapp.com),或确保自定义域名private.pages.dev已完成Firebase Auth的域名验证与配置。

修正后的firebaseConfig示例:

const firebaseConfig = {
  apiKey: "A...zY",
  authDomain: "p...79.firebaseapp.com", // 改为项目默认authDomain
  projectId: "p...79",
  storageBucket: "p...79.firebasestorage.app",
  messagingSenderId: "4...8",
  appId: "1:...:web:...",
  measurementId: "G-TN..."
};

2. 配置Firebase项目的授权域名

登录Firebase控制台,进入Authentication > 设置 > 授权域名,添加以下两个域名:

  • private.pages.dev(你的自定义域名)
  • p...79.firebaseapp.com(Firebase默认域名)

3. 调整重定向结果的处理时机

不要在应用初始化阶段直接调用getRedirectResult(),需等待Firebase Auth完全初始化完成。通过监听authStateChanges()确保Auth状态稳定后再处理重定向:

修改后的Dart代码:

// 等待Firebase Auth初始化完成
await FirebaseAuth.instance.authStateChanges().first;

try {
  UserCredential? credential = await FirebaseAuth.instance.getRedirectResult();
  print('credential: $credential');

  if (credential?.user != null) {
    print('Sign-in successful: ${credential.user}');
  } else if (FirebaseAuth.instance.currentUser == null) {
    print("initiating login");
    await FirebaseAuth.instance.signInWithRedirect(googleProvider);
  }
} on FirebaseAuthException catch (e) {
  switch (e.code) {
    case "provider-already-linked":
      logger.i("The provider has already been linked to the user.");
      break;
    case "invalid-credential":
      logger.i("The provider's credential is not valid.");
      break;
    case "credential-already-in-use":
      logger.i(
          "The account corresponding to the credential already exists, "
          "or is already linked to a Firebase User.");
      if (e.credential != null) {
        await FirebaseAuth.instance.signInWithCredential(e.credential!);
      }
      break;
    default:
      logger.i("Unknown error.");
  }
}

4. 更新Firebase SDK版本

确保pubspec.yaml中的firebase_core和firebase_auth依赖为最新稳定版,旧版本可能存在Web重定向兼容性问题:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.24.2 # 替换为最新版本
  firebase_auth: ^4.16.0 # 替换为最新版本

额外注意事项

  • 清除浏览器缓存和LocalStorage,避免旧认证状态干扰新流程。
  • 检查Google登录提供者是否已在Firebase控制台的Authentication > 登录方法中启用,并正确配置OAuth客户端ID(需包含Web应用的客户端ID)。

内容的提问来源于stack exchange,提问作者Bharel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:14:54