一、权限是什么?
权限是对特定资源的访问许可, 所谓权限控制,也就是确保用户只能访问到被分配的资源,而权限归根结底是请求的发起权,请求的发起可能有下面两种方式触发
- 页面加载触发
- 页面上的按钮点击触发
总的来说,所有的请求发起都触发前端路由或视图,所以我们可以从两方面入手,对触发权限的源头进行控制,最终要实现的目的是:
- 路由方面,用户登录后只能看待自己有权访问的导航菜单,也只能访问自己有权访问的路由地址,否则跳转到 404 提示页面
- 视图方面,用户只能看到自己有权浏览的内容和有权操控的控件
二、权限的分类
前端权限控制可以分为四个方面:
- 接口权限
- 按钮权限
- 路由权限
三、接口权限
接口权限目采用 jwt
的形式来验证,没有的话一般返回 404
,跳转到登录页面重新登录完成拿到 token
,将 token
存起来,在 axios
请求拦截器中进行拦截,每次请求的时候头部都携带 token
axios.interceptors.request.use(config => {
config.headers['token'] = cookie.get('token')
return config
})
axios.interceptors.response.use(res=>{},{response}=>{
if (response.data.code === 40099 || response.data.code === 40098) { //token过期或者错误
router.push('/login')
}
})
四、按钮权限
所谓按钮权限,不同的角色在同一个页面中可能看到不一样的按钮,(比如:管理员可以看到并使用 删除
按钮,但是普通用户却看不到)可以通过自定义指令 v-permission
进行按钮权限的判断:
directive/permission.js
import store from '@/store'
function checkPermission(el, binding) {
const { value } = binding
// 获取登录用户的角色
const roles = store.getters && store.getters.roles
// 判断 v-permission 传入的是否为角色数组(['admin','editor'])
if (value && value instanceof Array) {
if (value.length > 0) {
const permissionRoles = value
// 判断当前登录用户的角色是否在所传入的角色数组当中
const hasPermission = roles.some(role => {
return permissionRoles.includes(role)
})
if (!hasPermission) {
// 移除 v-permission 绑定的元素(让元素隐藏,没有权限的用户看不到)
el.parentNode && el.parentNode.removeChild(el)
}
}
} else {
throw new Error(`need roles! Like v-permission="['admin','editor']"`)
}
}
export default {
inserted(el, binding) {
checkPermission(el, binding)
},
update(el, binding) {
checkPermission(el, binding)
}
}
引入自定义的指令并进行局部注册(也可以全局注册)
在标签中使用自定义指令:
<span v-permission="['admin']" class="permission-alert">
Only
<el-tag class="permission-tag" size="small">admin</el-tag> can see this
</span>
<span v-permission="['admin','editor']" class="permission-alert">
Both
<el-tag class="permission-tag" size="small">admin</el-tag> and
<el-tag class="permission-tag" size="small">editor</el-tag> can see this
</span>
页面效果:
以下是一些关于 Vue
自定义指令的描述:
五、路由权限
在开发管理后台时,都会存在多个角色登录,登录成功后,不同的角色会展示不同的菜单路由。那么路由权限谁来做?前端还是后端,后端的验证是为了保证数据完整和操作安全的,而前端做验证是为了提高可用性和用户的体验。这里我对两种方式都做了讲解:
1. 前端控制
关于前端控制,前端有一份动态路由表,等到用户登录拿到用户的角色之后根据当前登录用户的角色去筛选出可以访问的路由,形成一份定制路由表,然后动态挂载路由。
思路:
- 创建
Vue
实例的时候将Vue-Router
挂载,但此时Vue-Router
挂载一些登录或不用权限的公用页面。
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import Layout from '@/layout'
import componentsRouter from './modules/components'
import chartsRouter from './modules/charts'
import tableRouter from './modules/table'
import nestedRouter from './modules/nested'
// 静态路由
export const constantRoutes = [
{
path: '/redirect',
component: Layout,
hidden: true,
children: [
{
path: '/redirect/:path(.*)',
component: () => import('@/views/redirect/index'),
},
],
},
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true,
},
{
path: '/auth-redirect',
component: () => import('@/views/login/auth-redirect'),
hidden: true,
},
{
path: '/404',
component: () => import('@/views/error-page/404'),
hidden: true,
},
{
path: '/401',
component: () => import('@/views/error-page/401'),
hidden: true,
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
{
path: 'dashboard',
component: () => import('@/views/dashboard/index'),
name: 'Dashboard',
meta: { title: 'Dashboard', icon: 'dashboard', affix: true },
},
],
},
{
path: '/documentation',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/documentation/index'),
name: 'Documentation',
meta: { title: 'Documentation', icon: 'documentation', affix: true },
},
],
},
{
path: '/guide',
component: Layout,
redirect: '/guide/index',
children: [
{
path: 'index',
component: () => import('@/views/guide/index'),
name: 'Guide',
meta: { title: 'Guide', icon: 'guide', noCache: true },
},
],
},
{
path: '/profile',
component: Layout,
redirect: '/profile/index',
hidden: true,
children: [
{
path: 'index',
component: () => import('@/views/profile/index'),
name: 'Profile',
meta: { title: 'Profile', icon: 'user', noCache: true },
},
],
},
]
// 动态路由
export const asyncRoutes = [
{
path: '/permission',
component: Layout,
redirect: '/permission/page',
alwaysShow: true, // will always show the root menu
name: 'Permission',
meta: {
title: 'Permission',
icon: 'lock',
roles: ['admin', 'editor'], // you can set roles in root nav
},
children: [
{
path: 'page',
component: () => import('@/views/permission/page'),
name: 'PagePermission',
meta: {
title: 'Page Permission',
roles: ['admin'], // or you can only set roles in sub nav
},
},
{
path: 'directive',
component: () => import('@/views/permission/directive'),
name: 'DirectivePermission',
meta: {
title: 'Directive Permission',
// if do not set roles, means: this page does not require permission
},
},
{
path: 'role',
component: () => import('@/views/permission/role'),
name: 'RolePermission',
meta: {
title: 'Role Permission',
roles: ['admin'],
},
},
],
},
{
path: '/icon',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/icons/index'),
name: 'Icons',
meta: { title: 'Icons', icon: 'icon', noCache: true },
},
],
},
componentsRouter,
chartsRouter,
nestedRouter,
tableRouter,
{
path: '/example',
component: Layout,
redirect: '/example/list',
name: 'Example',
meta: {
title: 'Example',
icon: 'el-icon-s-help',
},
children: [
{
path: 'create',
component: () => import('@/views/example/create'),
name: 'CreateArticle',
meta: { title: 'Create Article', icon: 'edit' },
},
{
path: 'edit/:id(\\d+)',
component: () => import('@/views/example/edit'),
name: 'EditArticle',
meta: { title: 'Edit Article', noCache: true, activeMenu: '/example/list' },
hidden: true,
},
{
path: 'list',
component: () => import('@/views/example/list'),
name: 'ArticleList',
meta: { title: 'Article List', icon: 'list' },
},
],
},
{
path: '/tab',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/tab/index'),
name: 'Tab',
meta: { title: 'Tab', icon: 'tab' },
},
],
},
{
path: '/error',
component: Layout,
redirect: 'noRedirect',
name: 'ErrorPages',
meta: {
title: 'Error Pages',
icon: '404',
},
children: [
{
path: '401',
component: () => import('@/views/error-page/401'),
name: 'Page401',
meta: { title: '401', noCache: true },
},
{
path: '404',
component: () => import('@/views/error-page/404'),
name: 'Page404',
meta: { title: '404', noCache: true },
},
],
},
{
path: '/error-log',
component: Layout,
children: [
{
path: 'log',
component: () => import('@/views/error-log/index'),
name: 'ErrorLog',
meta: { title: 'Error Log', icon: 'bug' },
},
],
},
{
path: '/excel',
component: Layout,
redirect: '/excel/export-excel',
name: 'Excel',
meta: {
title: 'Excel',
icon: 'excel',
},
children: [
{
path: 'export-excel',
component: () => import('@/views/excel/export-excel'),
name: 'ExportExcel',
meta: { title: 'Export Excel' },
},
{
path: 'export-selected-excel',
component: () => import('@/views/excel/select-excel'),
name: 'SelectExcel',
meta: { title: 'Export Selected' },
},
{
path: 'export-merge-header',
component: () => import('@/views/excel/merge-header'),
name: 'MergeHeader',
meta: { title: 'Merge Header' },
},
{
path: 'upload-excel',
component: () => import('@/views/excel/upload-excel'),
name: 'UploadExcel',
meta: { title: 'Upload Excel' },
},
],
},
{
path: '/zip',
component: Layout,
redirect: '/zip/download',
alwaysShow: true,
name: 'Zip',
meta: { title: 'Zip', icon: 'zip' },
children: [
{
path: 'download',
component: () => import('@/views/zip/index'),
name: 'ExportZip',
meta: { title: 'Export Zip' },
},
],
},
{
path: '/pdf',
component: Layout,
redirect: '/pdf/index',
children: [
{
path: 'index',
component: () => import('@/views/pdf/index'),
name: 'PDF',
meta: { title: 'PDF', icon: 'pdf' },
},
],
},
{
path: '/pdf/download',
component: () => import('@/views/pdf/download'),
hidden: true,
},
{
path: '/theme',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/theme/index'),
name: 'Theme',
meta: { title: 'Theme', icon: 'theme' },
},
],
},
{
path: '/clipboard',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/clipboard/index'),
name: 'ClipboardDemo',
meta: { title: 'Clipboard', icon: 'clipboard' },
},
],
},
{
path: 'external-link',
component: Layout,
children: [
{
path: 'https://github.com/PanJiaChen/vue-element-admin',
meta: { title: 'External Link', icon: 'link' },
},
],
},
// 404 page must be placed at the end !!!
{ path: '*', redirect: '/404', hidden: true },
]
const createRouter = () =>
new Router({
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes,
})
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher
}
export default router
-
用户登录后,获取用户角色,将
role
和路由表每个页面需要的权限作比较,生成用户可访问的路由表。 -
调用
router.addRoute(...accessRoutes)
添加用户可访问的路由。
permission.js
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect']
router.beforeEach(async (to, from, next) => {
NProgress.start()
document.title = getPageTitle(to.meta.title)
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
const { roles } = await store.dispatch('user/getInfo')
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
router.addRoute(...accessRoutes)
next({ ...to, replace: true })
} catch (error) {
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
store/modules/permission.js
import { asyncRoutes, constantRoutes } from '@/router'
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}
export function filterAsyncRoutes(routes, roles) {
const res = []
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
res.push(tmp)
}
})
return res
}
const state = {
routes: [],
addRoutes: [],
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
},
}
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
let accessedRoutes
if (roles.includes('admin')) {
accessedRoutes = asyncRoutes || []
} else {
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
},
}
export default {
namespaced: true,
state,
mutations,
actions,
}
- 使用
vuex
管理路由表,根据vuex
中可访问的路由渲染侧边栏组件。
layout/components/Sidebar/index.vue
store/getters.js
这里要注意一下,使用 addRoute
(动态路由) 会遇到的 bug
(404/白屏)
1、刷新页面跳转到 404
页面
解决方法是把 404
页改到路由配置的最末尾就可以了
2、解决刷新出现的白屏 bug
解决方法是在全局路由守卫中添加 next({ ...to, replace: true })
关于 next({ ...to, replace: true })
的解释如下:
next({
...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
replace: true // 重进一次, 不保留重复历史
})
前端控制路由权限的优缺点:
优点:
前端自己完成权限控制,避免了与后端沟通的麻烦(针对部分程序员)
缺点:
1.菜单信息是写死在前端,以后要改个显示文字或权限信息,需要重新修改然后编译。
2.每个路由的可访问角色都是写死的,不利于增加角色并分配权限
2. 后端控制
在项目上线之后,管理员添加了一个新角色,并且要给这个角色分配菜单。如果采用将路由表放在前端的话那么每个路由的可访问角色都是写死的 (meta{roles: ['admin']})
,要给新添加的角色分配菜单,只能改前端代码,显然不是很合适。因此可以将路由信息放在后端,后端将路由信息和角色关联起来,用户登录之后请求对应的接口拿到属于这个用户的路由信息(菜单)
,然后前端对返回的数据格式化,转换成符合 Vue-Router
的路由格式,然后动态挂载。
(1)后端接口返回数据
确定后端接口要返回的内容之前先要知道前端需要怎样的数据,前端需要的数据大概长这样:
这上面的数据是最理想的数据了,也就是如果后端返回这样的数据,那么前端直接用就行了。但这是不太可能的,因为后端的数据库表中可能有很多字段,为的就是覆盖到大多数情况,那么后端并不知道哪些东西对你前端来说是有用的,而且也不清楚数据组合的方式,要组合起来也很麻烦的,因为表是二维的,无法描述一些层级关系。所以,综上所述后端只能如数返回所有的字段,而前端要自己筛选和组合数据。后端返回的路由菜单是不包括login、404等页面的。前端这边还是需要写一份完整的路由列表。
(2)前端格式化路由数据
获取动态路由表的接口 @/api/user.js
export function getAsyncRoutes(roles) {
return request({
url: `/${roles}/menus`,
method: 'get'
})
}
获取路由表并保存到 Vuex
中 @/store/modules/permission.js
import formatRoutes from '@/utils/formatRoutes'
import Layout from '@/layout'
......
// actions
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
// 从服务器获取路由表
getAsyncRoutes(roles).then(routes => {
// 格式化路由表
const accessedRoutes = formatRoutes(routes, Layout) // formatRoutes函数会在后面放出来
// 将路由保存到Vuex中
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
格式化路由数据 @/utils/formatRoutes.js
function loadView(component) {
return (resolve) => require([`@/views/${component}`], resolve)
}
export default function formatRoutes(routes, Layout) {
const formatRoutesArr = []
routes.forEach(route => {
const router = {
meta: {}
}
const {
pid,
title,
path,
redirect,
component,
keep_alive,
icon,
name,
children
} = route
if (component === 'Layout') {
router['component'] = Layout
} else {
router['component'] = loadView(component)
}
if (redirect !== null) {
router['redirect'] = redirect
}
if (icon !== null) {
router['meta']['icon'] = icon
}
if (children && children instanceof Array && children.length > 0) {
router['children'] = formatRoutes(children)
}
if (name !== null) {
router['name'] = name
}
router['meta']['title'] = title
router['path'] = path
if (pid === 0) {
router['alwaysShow'] = true
}
router['meta']['noCache'] = !keep_alive
formatRoutesArr.push(router)
})
// 将404页面添加到最后面
formatRoutesArr.push({ path: '*', redirect: '/404', hidden: true })
return formatRoutesArr
}
全局路由守卫配置 @/permission.js
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect']
router.beforeEach(async(to, from, next) => {
// 开启页面进度条
NProgress.start()
// 设置标题
document.title = getPageTitle(to.meta.title)
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// 已登录,跳转到: '/'
next({ path: '/' })
NProgress.done() // 关闭页面进度条
} else {
// 是否通过用户信息拿到角色信息
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
// 登录过并且有角色信息,直接进入下一个路由
next()
} else {
try {
// 获取用户信息
const { roles } = await store.dispatch('user/getInfo')
// 重点在这。。。。
// 根据角色生成路由表
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// 动态添加路由
router.addRoute(...accessRoutes)
next({ ...to, replace: true })
} catch (error) {
console.log(error)
// 清除token,跳转登录页
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
// 访问的路径处于白名单中
next()
} else {
// 没有登录,跳转登录页
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
后端控制路由权限的优缺点:
优点:
保证了数据完整和操作安全
缺点:
项目不断的迭代会异常痛苦,前端新开发一个页面,后端还要配一下路由和权限