【问题标题】:How to block a user from going to a given url?如何阻止用户访问给定的 url?
【发布时间】:2021-06-22 11:48:28
【问题描述】:

在我的 vue 应用程序项目中,我创建了一个功能,该功能为权限太少的特定用户隐藏菜单项,如下所示:

<a :href="href" @click="navigate" v-if="wikiPanelVisibility()">
    // some code
</a>

wikiPanelVisibility() {
    if(currentUser.permission == 'All') {
      return true;
    } else return false; 
}

所以,好的,这会在 UI 上隐藏我的元素,并且当前登录的用户无法使用 url e.q 访问页面。 https://somelink.com/account/settings 通过点击 UI 中的锚点,但是当他写这个 url 时,他可以被重定向到这个页面,这里我有一个问题,如何阻止用户通过在浏览器中写到这个 url?

感谢您的帮助!

【问题讨论】:

  • 当浏览器访问受限的 url 时,测试用户的授权。如果通过,则显示页面,如果失败,则加载 403 页面(或主页,或任何您想要的)。
  • 如果你使用任何框架,你可以看看中间件的概念
  • 您应该在要重定向到的实际页面上使用授权。否则,如果您只是授权点击,只需输入按钮导航到的网址即可轻松避免。如果您使用的是 ASP.NET Core,则可以使用 Identity 来授权用户。
  • 无法阻止在浏览器中手动更改网址。另外,请不要使用不相关的标签 - 否则,请解释这与 css 的关系

标签: javascript html css typescript vue.js


【解决方案1】:

您需要使用 Vue 路由器并按照文档 [Navigation Guards] 中的说明在 beforeEach 循环上配置验证:https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

你会得到这样的东西:

   router.beforeEach(async (to, from, next) => {
     const currentUser = store.state.currentUser
     if ( currentUser.permission !== 'All) {
       next(loginPage)
     } else {
       next()
     }
   })

【讨论】:

    【解决方案2】:

    您可以使用导航守卫将该逻辑应用于特定页面Navigation Guards

    在你的路由文件中设置这样的路由:

    {
        path:'/yourPath',
        meta:{guest:false},
        component:YourComponent
    }
    

    如果未通过身份验证,从页面将用户重定向到 /login 页面的示例:

    // BAD
        router.beforeEach((to, from, next) => {
          if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
          // if the user is not authenticated, `next` is called twice
          next()
        })
    // GOOD
    router.beforeEach((to, from, next) => {
      if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
      else next()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      相关资源
      最近更新 更多