【问题标题】:Vuejs router navigation guard working on first request, ignoring second timeVuejs路由器导航守卫在第一次请求时工作,第二次忽略
【发布时间】:2020-05-20 10:15:01
【问题描述】:

(我是 Vue 新手) 我在我的路由器上实现了一个导航保护,它在从另一条路线导航时工作。守卫将用户导航到拒绝访问页面。此时导航菜单仍然从拒绝访问页面可见,这意味着用户可以尝试再次加载他们被拒绝访问的页面。如果用户确实尝试这样做,他们之前被拒绝访问的页面会加载,我想阻止这种情况发生。似乎以某种方式绕过了警卫?

谢谢

if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
next({name: 'login'});

} else if (to.matched.some(record => record.meta.roles)) {

var userRoles = JSON.parse(loggedIn).roles;
to.meta.roles.forEach(function (role) {
  if (userRoles.includes(role))
    next();
});  
  next({ name:'accessdenied'});    
}

路由器入口:-

{
path: '/pageA',
name: 'pageA',
component: pageA,
meta: { requiresAuth: true, roles: ['role1', 'role2'] },
beforeEnter(routeTo, routeFrom, next) {
  store.dispatch('fetchSomeData').then(() => {
    next()
  })
}

导航条目:-

<router-link :to="{name: 'pageA'}">
            <h1 class="mb-0 h5 ml-4 z-app-header-title">Page A</h1>
 </router-link>

【问题讨论】:

  • 我不明白你的意思,所以你说当他们已经在 AccessDenied 页面上,并且他们点击导航菜单时,该页面将再次加载 AccessDenied 页面,你不想要吗?
  • 对不起,没有。因此,他们尝试加载“页面 a”,但他们无权访问并被发送到“拒绝访问”。顶部有一个菜单,他们可以单击链接再次加载“页面 a”。如果他们点击它,它就会加载。就好像它以某种方式绕过了守卫。我在想我的路由器代码一定是不正确的,它认为它已成功加载“页面 a”或其他东西,并且没有第二次检查。但我仍然在掌握 Vue。谢谢
  • 对于这段代码,它对所有变量都不是很清楚,您能否发布更多路由器 js 文件的代码,以及导航菜单,特别是与用户角色相关的部分(如果有)。外面可能有一些错误

标签: vue.js vue-router


【解决方案1】:

要正确保护路线,请使用类似的东西

{
path: '/pageA',
name: 'pageA',
component: pageA,
meta: { requiresAuth: true, roles: ['role1', 'role2'] },
beforeEnter(routeTo, routeFrom, next) {
  if(!store.getters.loggedIn) next({name: 'login'});
  else if(!routeTo.meta.roles.includes(store.getters.userRole)) next({name: 'accessdenied
'});
  else next();
}

要保护所有路线 - 使用类似的东西

router.beforeEach((to, from, next) =>
{
  if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) next({name: 'login'});

  else if (to.meta.roles)
  {
    const userRole = JSON.parse(loggedIn).role; // the role of the current user
    if(to.meta.roles.includes(userRole)) next();
    else next({ name:'accessdenied'});    
  }
  else next();
});

【讨论】:

  • 谢谢,我正在使用上面的“保护所有路由”选项,它第一次工作 - 我看到访问被拒绝页面。如果您查看上面的“导航条目”,则在加载时访问被拒绝页面上可见。如果我单击导航条目,而不是仍然显示访问被拒绝页面,“pageA”加载即访问被拒绝页面消失,它加载第一次被阻止的 PageA。就像第二次忽略了 beforeEach 一样。谢谢。
  • 请忽略,我完全愚蠢,漫长的一周。谢谢!
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2018-02-21
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2015-10-05
相关资源
最近更新 更多