【问题标题】:Vue router is safe?Vue路由器安全吗?
【发布时间】:2021-01-01 17:58:50
【问题描述】:

我正在用 vue 开发一个网络,我意识到如果我把它放在控制台中

document.getElementById('app').__vue__.$router.push("some_route")

尽管我在 beforeEach 导航保护 (requireAuth) 中声明了元数据,但它仍然有效。 我需要创建一些随机用户无法访问的路由,在烧瓶中制作的 api 中,我返回一个令牌和一个角色,如果我尝试通过任何导航器中的地址栏访问,这工作正常但是当我通过控制台访问时不是,路由器在没有认证的情况下推送路由。

router.beforeEach(async (to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    let user = JSON.parse(localStorage.getItem('user')) //user is a json with a jwt token

    if (user && user.token){
      
      await user_service.isLogged(to.path).then(response => {
       //wait for a response from the server if the token is valid
        switch (response.status){
          case 200:
            next()
            break;

          case 401:
            next({path: '/login'})
            break;
          
          case 403:
            next({path: '/403'})
            break;
        }
      })
    }else{
      next({path: '/login'})
    }

  }
  next()
})

感谢任何反馈。谢谢!

【问题讨论】:

  • 如果这确实有效,那么您的导航保护可能有问题。如果您不显示代码,则无法为您提供帮助
  • 是的!也许是这样,我觉得奇怪的是,如果我尝试像普通用户一样访问路由,使用按钮或更改地址栏中的 url 它工作正常!
  • 已更新,感谢您的早日答复
  • 您能否展示一个已验证和未验证路由的路由元属性示例
  • 您能提供一个工作示例吗? (使用codesandbox.io)。

标签: javascript vue.js console vue-router


【解决方案1】:

没有什么可以阻止最终的 next() 运行,这会使您的整个导航守卫变得多余。

要么将其包装在 else 块中,例如

if(to.matched.some(record => record.meta.requiresAuth)) {
  // your code
} else {
  next()
}

或更改您的代码以在适当的位置退出(通过return

router.beforeEach(async (to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    let user = JSON.parse(localStorage.getItem('user'))

    if (user && user.token){
      await user_service.isLogged(to.path).then(response => {
       //wait for a response from the server if the token is valid
        switch (response.status){
          case 200:
            return next()
          case 403:
            return next({path: '/403'})
          case 401:
          default:
            return next({path: '/login'})
        }
      })
    } else {
      return next({path: '/login'})
    }
  }
  next()
})

【讨论】:

  • 鉴于此答案已被 OP 接受,如果您投反对票,请留下关于 为什么 的评论
  • 我是 Stack Overflow 的新手,我投了赞成票,但它不会改变分数,也许你也可以帮助我。顺便说一句,我来自阿根廷,我的英语很基础
  • @Lucas 不是你的伴侣。在你接受我的回答后有人出现了,并且没有说明原因就给了它一个否决票。如果我不知道答案有什么问题,就很难改进我的答案
猜你喜欢
  • 2021-02-08
  • 1970-01-01
  • 2020-06-26
  • 2019-09-24
  • 2019-05-02
  • 2018-11-17
  • 2020-06-28
  • 1970-01-01
  • 2017-03-06
相关资源
最近更新 更多