【问题标题】:Firebase Auth Web: Logout with page reloadFirebase Auth Web:注销并重新加载页面
【发布时间】:2022-02-10 11:31:29
【问题描述】:

我将 Firebase 与 VueJS 一起使用。到目前为止,注册,登录工作正常,但是一旦我用 F5 重新加载页面或加载页面并直接写入浏览器地址栏,然后身份验证会话被终止,用户就不再登录了。只要我不重新加载页面,它就可以正常工作,即使我单击路由链接或被重定向到其他页面,用户会话也会保持活动状态。顺便说一句,我在哪里重新加载页面并不重要。

我的登录方式:

firebase.auth().signInWithEmailAndPassword(this.username, this.password).then(
                    (user) => {
                        if (user.emailVerified === false) {
                            firebase.auth().signOut()
                        } else {
                            // redirect to lobby page if user is verified and signed in
                            this.$router.push('/lobby')
                        }
                    },
                    function(err) {
                        console.log(err.message)
                    }
                )

【问题讨论】:

    标签: node.js firebase vuejs2 firebase-authentication


    【解决方案1】:

    你需要调用firebase.auth().onAuthStateChanged来检测用户是否登录。

    当身份验证状态发生变化时,会在 UI 线程中调用此方法:

    • 在监听器注册之后

    • 当用户登录时

    • 当前用户退出时

    • 当当前用户发生变化时

    Source

    示例用法可以是这样的:

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        if (user.emailVerified === false) {
          firebase.auth().signOut()
        } else {
          this.$router.push('/lobby')
        }
      } else {
        // will get to here from a logout event
        // this.$router.push('/login')
      }
    }
    

    【讨论】:

      【解决方案2】:

      在你的 main.js 文件中使用它:

      firebase.auth().onAuthStateChanged(() => {
      if (!app) {
          app = createApp(App).use(store).use(router).mount('#app')
      }})
      

      Firebase 将在创建 Vue 应用之前运行。

      【讨论】:

        猜你喜欢
        • 2014-10-04
        • 1970-01-01
        • 1970-01-01
        • 2017-08-10
        • 1970-01-01
        • 2021-02-15
        • 2018-01-17
        • 2016-05-24
        • 2019-10-31
        相关资源
        最近更新 更多