首页 > 解决方案 > 手动输入 URL 后的 Vue.js 身份验证

问题描述

在我的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 that go :to="{ name: 'SomeComponent' }".

当任何用户(注册或匿名)尝试通过键入或复制粘贴 url 在应用程序中导航时,应用程序将自动将其发送到登录页面。

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

它不会保持错误:已登录currentUserState === truecurrentUserState === falsecurrentUserStatetrue

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

标签: node.jsfirebasevue.jsfirebase-authenticationvue-router

解决方案


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
    })
});

推荐阅读