【问题标题】:Vue.js authentication after manually entering URL手动输入 URL 后的 Vue.js 身份验证
【发布时间】:2019-03-17 05:24:37
【问题描述】:

在我的routes数组main.js中,我已经设置了

meta : { requiresAuth: true }

对于除UserLogin 页面之外的所有组件。

关于导航分辨率,我在每条路线前都设置了如下检查:

router.beforeEach((to, from, next) => {
    const currentUser = firebase.auth().currentUser;
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const currentUserState = !!currentUser;

    console.table({ currentUserState, requiresAuth });

    if (requiresAuth && !currentUser) {
        next('/login');
    } else {
        next();
    }
}

使用此设置,一切几乎都按预期/预期工作。登录用户可以去任何地方,匿名用户被重定向到localhost/login

但是,这种检查和重定向仅在用户通过单击 Web 应用程序中的链接进行导航时起作用(这些链接都是 <router-link>s 和 :to="{ name: 'SomeComponent' }"

当任何用户(注册或匿名)尝试通过键入或复制粘贴 URL 来浏览应用程序时,应用程序会自动将其发送到登录页面。

从console.table 输出中,我可以看到手动输入url 总是导致currentUserState 为false。

它不会保持错误:已登录 (currentUserState === true) 的用户,然后手动导航到某处 (currentUserState === false),其 currentUserState 恢复为 true

我只能隐约猜测问题与渲染和firebase.auth()有关。

【问题讨论】:

  • 需要看看你是如何初始化firebase的......我猜你是在初始化firebase之前设置路由所以当用户输入一个url时,路由器在firebase初始化之前被调用没有用户
  • @AaronSaunders 我有一个 database.js 文件,我的配置对象所在的位置。 app = firebase.initializeApp(confg) 发生在这个文件中,db = app.database(); 被导出。 main.js 中未调用 database.js
  • firebase.initializeApp(confg) 不解析当前用户...
  • @AaronSaunders 感谢您的回复。我需要澄清你所说的“解决”当前用户的意思,或者更确切地说,如何在router.beforeEach 回调中提供调用firebase.auth().currentUser 的能力main.js

标签: node.js firebase vue.js firebase-authentication vue-router


【解决方案1】:
firebase.initializeApp(config)

// you need to let firebase try and get the auth state before instantiating the 
// the Vue component, otherwise the router will be created and you haven't 
// resolved whether or not you have a user

firebase.auth().onAuthStateChanged(function(user) {
    app = new Vue({
      el: '#app',
      template: '<App/>',
      components: { App },
      router
    })
});

【讨论】:

    【解决方案2】:

    我已经找到了解决这个错误的方法。

    在我的 Vuex store.js 中,状态快照存储在 localStorage 中。此快照会在商店本身发生更改时更新,因此 localStorage 备份始终与 Vue.js 应用程序本身的实际状态保持同步。

    store.subscribe((mutation, state) => {
      localStorage.setItem('store', JSON.stringify(state));
    });
    

    这个store.subscribe 设置在我的store.js 中,就在导出行之前。

    在store中也定义了一个名为initStore的函数,如下

    initStore(state) {
      if (localStorage.getItem('store')) {
        this.replaceState(Object.assign(state, JSON.parse(localStorage.getItem('store'))));
      }
    },
    

    在我的 store 对象之后,它立即被调用 store.commit('initStore').

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 1970-01-01
      • 2018-05-06
      • 2022-07-16
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 2011-06-18
      相关资源
      最近更新 更多