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

Firebase谷歌认证突然失效,回调返回user为null求排查

Firebase谷歌认证onAuthStateChanged返回user为null的排查原因

Firebase谷歌认证突然无法正常工作,调试script.js时发现onAuthStateChanged回调返回的user为null,以下是基于官方文档实现的代码,可从以下几个方向排查原因:

window.addEventListener('load', function () {

  // FirebaseUI config.
  var uiConfig = {
    signInSuccessUrl: '/',
    signInOptions: [
      // Comment out any lines corresponding to providers you did not check in
      // the Firebase console.
      firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      //firebase.auth.EmailAuthProvider.PROVIDER_ID,
      //firebase.auth.FacebookAuthProvider.PROVIDER_ID,
      //firebase.auth.TwitterAuthProvider.PROVIDER_ID,
      //firebase.auth.GithubAuthProvider.PROVIDER_ID,
      //firebase.auth.PhoneAuthProvider.PROVIDER_ID

    ],
    // Terms of service url.
    tosUrl: '<your-tos-url>'
  };

  firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      // User is signed in, so display the "sign out" button and login info.
      //document.getElementById('sign-out').hidden = false;

      console.log(`Signed in as ${user.displayName} (${user.email})`);
      user.getIdToken().then(function (token) {
        // Add the token to the browser's cookies. The server will then be
        // able to verify the token against the API.
        // SECURITY NOTE: As cookies can easily be modified, only put the
        // token (which is verified server-side) in a cookie; do not add other
        // user information.
        document.cookie = "token=" + token;
      });
    } else {
      // User is signed out.
      // Initialize the FirebaseUI Widget using Firebase.
      var ui = new firebaseui.auth.AuthUI(firebase.auth());
      // Show the Firebase login button.
      ui.start('#firebaseui-auth-container', uiConfig);
      // Update the login state indicators.


      // Clear the token cookie.
      document.cookie = "token=";
    }
  }, function (error) {
    console.log(error);
    alert('Unable to log in: ' + error)
  });
});

可能的原因:

  • Firebase项目配置异常:检查Firebase控制台中谷歌登录提供商是否被禁用;确认OAuth 2.0客户端ID有效,且当前网站域名已添加到“授权域”列表中。
  • 浏览器存储问题:浏览器的LocalStorage或Cookie被清除,导致Firebase无法持久化用户会话;尝试用无痕模式测试,排除缓存或浏览器插件干扰。
  • SDK版本兼容问题:若近期更新过Firebase SDK,可能存在API变更(比如PROVIDER_ID常量是否被替换),尝试回退到之前稳定版本,或对照官方文档检查API是否有调整。
  • 代码逻辑缺陷:每次user为null时都会重新实例化FirebaseUI,重复启动可能引发会话异常;建议将FirebaseUI初始化移到回调外部,仅在首次需要时调用ui.start()。
  • 认证令牌失效:用户的认证令牌过期且自动刷新失败,查看浏览器控制台是否有令牌相关的错误日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:00:24