如何使用Firebase保持登录用户的身份? [英] How can you persist a logged-in user with firebase?

查看:57
本文介绍了如何使用Firebase保持登录用户的身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢您阅读这个新手的问​​题.

Thanks a bunch for reading this newbie's question.

因此,有一个ReactJS应用正在使用Firebase进行身份验证.

So, there is a ReactJS app which is using firebase for its authentication.

每次刷新页面时,用户将永远消失,直到您使用重定向的登录页面登录为止.

Everytime the page is refreshed, the user is gone forever until you login in with the redirected login page.

到目前为止已经做了什么?

What have been done so far?

好吧,在仔细研究了所有可能的Stackoverflows完美答案之后,完成了以下工作:

Well, after plodding through all the possible Stackoverflows flowing flawless answers, following have been done:

  1. 实现了onAuthStateChanged()函数,如下所示:

  firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                console.log('user is logged in');
            } else {
                console.log('user is logged out now')
            }
        });

  1. 设置持久性(似乎是一个沉默的工作者),如下所示:

 firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE)
        .then(function () {
          console.log("successfully set the persistence");
    
        })
        .catch(function (error) {
          console.log("failed to ser persistence: " + error.message)
        });

每个页面重新加载都会使用户注销,就像这样.走了!没有什么.甚至没有灰尘!

Every page reloads logs the user out just like that. Gone!. Nothing. Not even a trace of its dust!

为了更好地理解此易碎代码,我可以为您提供以下控制台消息的屏幕截图.

To have a better understanding of this crippling code, I can give you the following screenshots of the console messages.

您在登录时得到了这个

以及刷新页面时的以下内容.

And the following when the page is refreshed.

为什么应用了上述方法后仍会弹出此错误?

Why do you think this error pops up even after applying the above?

再次感谢!

Update1:​​记下了setPersistence.事实证明,即使页面重新加载到登录名之后,用户也已登录.

Update1: Took down the setPersistence thing. And it turns out that the user is logged in even after page reloads to the login.

更新2:刷新页面时实际上实际上是将用户拉出.现在这就是我们需要在这里解决的问题.你们怎么看?

Update 2: User is actually get pulled out when refreshing the page. Now that's what we need to solve here. What do you guys think?

推荐答案

Firebase Auth SDK默认启用持久性.如果您想要该默认行为,则完全不要调用 firebase.auth().setPersistence().只需使用 onAuthStateChanged 即可知道持久化用户对象何时首次可用.

The Firebase Auth SDK enables persistence by default. If you want that default behavior, don't call firebase.auth().setPersistence() at all. Just use onAuthStateChanged to know when the persisted user object is first available.

这篇关于如何使用Firebase保持登录用户的身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆