【问题标题】:Firebase is not persisting authentication stateFirebase 没有保持身份验证状态
【发布时间】:2021-03-04 08:23:54
【问题描述】:

我想知道如何使用 firebase 保持身份验证状态。我正在做的是尝试设置持久性状态,我这样做:

login.addEventListener('click', function (e) {
    e.preventDefault();

    var email = emailInput.value;
    var password = passwordInput.value;

    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
    .then(function() {
        auth.signInWithEmailAndPassword(email, password)
        .then(function (user) {
         })
        .catch(function (error) {
                alert(error);
        });
    })
});

问题是,当我刷新我的网络应用程序时,会话似乎没有持续存在。它将用户重定向回登录屏幕,这根本不是所需的输出。所需的输出将保存用户的会话,并且用户能够通过应用程序而不会出现强制再次登录的问题。

我正在关注 firebase 文档:

https://firebase.google.com/docs/auth/web/auth-state-persistence

【问题讨论】:

  • “当我刷新我的 web 应用程序时,会话似乎没有被持久化”你是如何确定的?您的代码目前都没有处理恢复的身份验证状态。为此,请使用此处第一个示例所示的身份验证状态侦听器:firebase.google.com/docs/auth/web/…
  • 还要检查是否需要显式设置持久性。在大多数环境中,默认情况下会正确设置。
  • 尝试制作 firebase.auth.Auth.Persistence.SESSION

标签: javascript firebase firebase-authentication


【解决方案1】:

如果您想知道用户之前是否在新页面加载时登录过您的网站,您应该使用auth state observer 来接收回调,通知您何时首次知道用户已登录。它页面加载时不会立即触发 - SDK 需要一些时间来加载用户帐户并确定其是否有效。

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

不要使用firebase.auth().currentUser 来确定用户之前是否已登录。页面加载时它最初始终为空。欲了解更多信息,read this blog

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2019-10-24
    • 2020-12-05
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多