Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前后端分离下的用户认证和鉴权实践(六) 前端的路由控制和动态渲染 #7

Open
ZhuXS opened this issue Oct 16, 2017 · 0 comments

Comments

@ZhuXS
Copy link
Owner

ZhuXS commented Oct 16, 2017

前端要根据用户权限进行路由控制,并对组件进行动态渲染

  • 在一个页面中,用户只能看到其权限相关的组件和菜单项。
  • 依照用户的权限对用户的路由跳转加以控制,当前用户无权访问的url不能暴露给用户。
  • 要避免用户可以访问界面,在调用后端接口时却返回无权限的情况。

挑战

  • 由于前后端分离,后端无法对前端的路由进行控制
  • 前端页面刷新后,数据无法保持
  • 不同的用户需要根据其权限动态挂载不同的路由

解决方案

  • 利用Vuex维护用户的Role、Permission等相关用户信息,方便在不同的组件之间进行状态共享管理
    const getters = {
      status: state => state.user.status,
      username: state => state.user.username,
      name: state => state.user.name,
      roles: state => state.user.roles,
      addRouters: state => state.permission.addRouters
    }
  • 根据路由中的meta字段,结合用户的权限信息,过滤该用户有权限的路由表
    {
          path: "/admin",
          component: _import('admin/index'),
          //redirect: '/dashboard',
          meta:{
              role: ['Admin']
          },
          name: "admin"
    }
  • 利用VueRouter的addRoutes()新特性,动态挂载路由
  
  function filterAsyncRouter(asyncRouterMap,roles) {
      const accessedRouters = asyncRouterMap.filter(route => {
          if(hasPermission(roles,route)){
              if(route.children && route.children.length){
                  route.children = filterAsyncRouter(route.children,roles)
              }
              return true
          }
          return false
      })
      return accessedRouters
  }

总结

  • 预先定义所有的路由,包括通用路由和权限限制的路由,在有权限限制的路由的meta字段中添加权限信息
  • 用户登录后获取用户的权限信息并保存
  • 根据用户的权限信息过滤路由
  • 挂载过滤得到的路由
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant