当用户信息来自异步函数时实现 vue.js 路由器保护

Implementing vue.js router guards when user infos come from asynchronous function

我正在开发一个 Vue.js 应用程序,我需要实施路由器防护以根据用户角色限制访问并防止未登录的用户访问该应用程序。 登录过程涉及一个外部应用程序(特别是 WSO2 Identity Server),检索到的用户信息保存在 Vuex 存储中。 问题在于登录功能是异步的,因此当执行路由器守卫时,用户信息尚不可用。为了让它工作,我在匿名异步函数中调用了登录函数,并将守卫放在它的 then 块中。 由于我没有在互联网上找到这种方法的例子,我想知道它是否正确或者有更好的方法来处理这个问题。提前谢谢大家。

这是我的路由器代码示例:

... router code

(async function() {
  // get user data and saves them in the vuex store
  await userService.initUserData();
})().then( function() {
    const isAuthenticated = store.getters.getIsAuthenticated;
    const userRole = store.getters.getUserRole;

    router.beforeEach((to, from, next) => {
      // check if user is logged in,
      // if not redirect to login page (LoginPage)
      if (to.name !== 'LoginPage' && !isAuthenticated) {
        next({ name: 'LoginPage' });
      } else {
        if (to.meta.customerAuth) {
          if (userRole === 'Customer') {
            next();
          } else if (userRole === 'Admin') {
            next({ name: 'AdminView' });
          } else {
            next({ name: 'LoginPage' });
          }
        } else if (to.meta.adminAuth) {
          if (userRole === 'Admin') {
            next();
          } else if (userRole === 'Customer') {
            next({ name: 'CustomerView' });
          } else {
            next({ name: 'LoginPage' });
          }
        }
      }
    })
  }
);

您应该将您的用户信息保存在本地存储中,这样您就不需要在每次刷新页面时都获取权限。

如果权限因令牌的有效性而发生更改,您可以做的是 return 一个 401 HTTP 代码,该代码将注销并重定向到登录以获取具有新权限的新令牌。

当您将用户信息存储在存储器中时,您无需等待配置您的守卫。

关键是:登录应该只发生一次,如果你刷新你不应该再次登录