赞
踩
权限控制是确保用户只能访问其被授权的资源和执行其被授权的操作的重要方面。而前端权限归根结底是请求的发起权,请求的发起可能有下面两种形式触发
总体而言,权限控制可以从前端路由和视图两个方面入手,以确保对触发权限的源头进行有效的控制。最终目标是确保用户在整个应用程序中的访问和操作都受到适当的权限限制,从而保护敏感数据和功能:
前端权限控制通常涉及以下四个方面:
数据权限控制:
按钮/操作权限控制:
路由权限控制:
菜单权限控制:
这四个方面的权限控制通常需要配合后端进行,因为前端的权限控制只是一种辅助手段,真正的权限验证和控制应该在后端进行。前端的权限控制主要是为了提升用户体验,使用户在界面上只看到和能够操作其有权限的内容。在实现这些权限控制时,通常会使用一些全局路由守卫、指令、状态管理等技术手段。
接口权限
接口权限目前一般采用jwt的形式来验证,没有通过的话一般返回401,跳转到登录页面重新进行登录。 登录完拿到token,将token存起来,通过axios请求拦截器进行拦截,每次请求的时候头部携带token。
// Axios请求拦截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
路由权限控制
方案一
初始化即挂载全部路由,并且在路由上标记相应的权限信息,每次路由跳转前做校验
import { RouteRecordRaw } from 'vue-router'; const routerMap: RouteRecordRaw[] = [ { path: '/permission', component: () => import('@/layouts/Layout.vue'), redirect: '/permission/index', children: [ { path: 'index', component: () => import('@/views/permission/index.vue'), name: 'Permission', meta: { title: 'permission', icon: 'lock', roles: ['admin', 'editor'], // you can set roles in root nav alwaysShow: true, // will always show the root menu }, }, { path: 'page', component: () => import('@/views/permission/page.vue'), name: 'PagePermission', meta: { title: 'pagePermission', roles: ['admin'], // or you can only set roles in sub nav }, }, { path: 'directive', component: () => import('@/views/permission/directive.vue'), name: 'DirectivePermission', meta: { title: 'directivePermission', // if do not set roles, means: this page does not require permission }, }, ], }, ]; export default routerMap;
这种方式存在以下四种缺点:
方案二
初始化的时候先挂载不需要权限控制的路由,比如登录页,404等错误页。如果用户通过URL进行强制访问,则会直接进入404,相当于从源头上做了控制
登录后,获取用户的权限信息,然后筛选有权限访问的路由,在全局路由守卫里进行调用addRoutes添加路由
import router from './router'; import store from './store'; import { Message } from 'element-ui'; import NProgress from 'nprogress'; // progress bar import 'nprogress/nprogress.css'; // progress bar style import { getToken } from '@/utils/auth'; // getToken from cookie import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'; NProgress.configure({ showSpinner: false }); // NProgress Configuration // permission judge function function hasPermission(roles: string[], permissionRoles: string[] | undefined): boolean { if (roles.indexOf('admin') >= 0) return true; // admin permission passed directly if (!permissionRoles) return true; return roles.some(role => permissionRoles.indexOf(role) >= 0); } const whiteList = ['/login', '/authredirect']; // no redirect whitelist router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => { NProgress.start(); // start progress bar if (getToken()) { // determine if there has token /* has token*/ if (to.path === '/login') { next({ path: '/' }); NProgress.done(); // if the current page is dashboard will not trigger afterEach hook, so manually handle it } else { if (store.getters.roles.length === 0) { // determine if the current user has pulled the user_info information store.dispatch('GetUserInfo').then(res => { // pull user_info const roles = res.data.roles; // note: roles must be an array, such as: ['editor','develop'] store.dispatch('GenerateRoutes', { roles }).then(() => { // generate accessible route table based on roles router.addRoute(store.getters.addRouters[0]); // dynamically add accessible route table next({ ...to, replace: true }); // hack method to ensure that addRoutes has completed, set the replace: true so the navigation will not leave a history record }); }).catch((err) => { store.dispatch('FedLogOut').then(() => { Message.error(err || 'Verification failed, please login again'); next({ path: '/' }); }); }); } else { // If there is no need to dynamically change permissions, you can directly call next() to delete the following permission judgment ↓ if (hasPermission(store.getters.roles, to.meta.roles)) { next(); } else { next({ path: '/401', replace: true, query: { noGoBack: true } }); } // You can delete above ↑ } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // in the login whitelist, enter directly next(); } else { next('/login'); // otherwise, redirect all to the login page NProgress.done(); // if the current page is login will not trigger the afterEach hook, so manually handle it } } }); router.afterEach(() => { NProgress.done(); // finish progress bar });
按需挂载,路由就需要知道用户的路由权限,也就是在用户登录进来的时候就要知道当前用户拥有哪些路由权限
这种方式也存在了以下的缺点:
菜单权限
菜单权限通常指在一个应用程序或系统中,对用户或用户组在系统菜单中的访问和操作进行控制的功能。具体来说,菜单权限包括了用户能够看到和操作的菜单项、导航链接或按钮等。
方案一
菜单与路由分离,菜单由后端返回
前端定义路由信息
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
}
name字段都不为空,需要根据此字段与后端返回菜单做关联,后端返回的菜单信息中必须要有name对应的字段,并且做唯一性校验
全局路由守卫里做判断
import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'; import { ElMessage } from 'element-plus'; import { getToken } from '@/utils/auth'; // getToken from cookie import store from '@/store'; import Util from '@/utils/util'; const whiteList = ['/login', '/authredirect']; // no redirect whitelist const router = createRouter({ history: createWebHashHistory(), routes: [], }); function hasPermission(route: RouteRecordRaw, accessMenu: any[]): boolean { if (whiteList.indexOf(route.path) !== -1) { return true; } const menu = Util.getMenuByName(route.name as string, accessMenu); if (menu.name) { return true; } return false; } router.beforeEach(async (to, from, next) => { if (getToken()) { const userInfo = store.state.user.userInfo; if (!userInfo.name) { try { await store.dispatch('GetUserInfo'); await store.dispatch('updateAccessMenu'); if (to.path === '/login') { next({ name: 'home_index' }); } else { next({ ...to, replace: true }); // 菜单权限更新完成,重新进入当前路由 } } catch (e) { if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 next(); } else { next('/login'); } } } else { if (to.path === '/login') { next({ name: 'home_index' }); } else { if (hasPermission(to, store.getters.accessMenu)) { Util.toDefaultPage(store.getters.accessMenu, to, router.options.routes as RouteRecordRaw[], next); } else { next({ path: '/403', replace: true }); } } } } else { if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 next(); } else { next('/login'); } } const menu = Util.getMenuByName(to.name as string, store.getters.accessMenu); Util.title(menu.title); }); router.afterEach((to) => { window.scrollTo(0, 0); }); export default router;
每次路由跳转的时候都要判断权限,这里的判断也很简单,因为菜单的name与路由的name是一一对应的,而后端返回的菜单就已经是经过权限过滤的
如果根据路由name找不到对应的菜单,就表示用户有没权限访问
如果路由很多,可以在应用初始化的时候,只挂载不需要权限控制的路由。取得后端返回的菜单后,根据菜单与路由的对应关系,筛选出可访问的路由,通过addRoutes动态挂载
这种方式的缺点:
方案二
菜单和路由都由后端返回
前端统一定义路由组件
const Home = () => import("../pages/Home.vue");
const UserInfo = () => import("../pages/UserInfo.vue");
export default {
home: Home,
userInfo: UserInfo
};
后端路由组件返回以下格式
[
{
name: "home",
path: "/",
component: "home"
},
{
name: "home",
path: "/userinfo",
component: "userInfo"
}
]
在将后端返回路由通过addRoutes动态挂载之间,需要将数据处理一下,将component字段换为真正的组件
如果有嵌套路由,后端功能设计的时候,要注意添加相应的字段,前端拿到数据也要做相应的处理
这种方法也会存在缺点:
按钮权限
但是如果页面过多,每个页面页面都要获取用户权限role和路由表里的meta.btnPermissions,然后再做判断
通过自定义指令进行按钮权限的判断
首先配置路由
{ path: '/permission', component: Layout, name: '权限测试', meta: { btnPermissions: ['admin', 'supper', 'normal'] }, //页面需要的权限 children: [{ path: 'supper', component: _import('system/supper'), name: '权限测试页', meta: { btnPermissions: ['admin', 'supper'] } //页面需要的权限 }, { path: 'normal', component: _import('system/normal'), name: '权限测试页', meta: { btnPermissions: ['admin'] } //页面需要的权限 }] }
自定义权限鉴定指令
import { DirectiveBinding } from 'vue'; /** 权限指令 **/ const has = { mounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) { // 获取页面按钮权限 let btnPermissionsArr: string[] = []; if (binding.value) { // 如果指令传值,获取指令参数,根据指令参数和当前登录人按钮权限做比较。 btnPermissionsArr = Array.of(binding.value); } else { // 否则获取路由中的参数,根据路由的btnPermissionsArr和当前登录人按钮权限做比较。 btnPermissionsArr = vnode.appContext.config.globalProperties.$route.meta.btnPermissions; } if (!vnode.appContext.config.globalProperties.$_has(btnPermissionsArr)) { el.parentNode?.removeChild(el); } } }; // 权限检查方法 const $_has = function (value: string[]): boolean { let isExist = false; // 获取用户按钮权限 let btnPermissionsStr = sessionStorage.getItem('btnPermissions'); if (btnPermissionsStr == undefined || btnPermissionsStr == null) { return false; } if (value.indexOf(btnPermissionsStr) > -1) { isExist = true; } return isExist; }; export { has, $_has };
请注意以下几点:
在使用的按钮中只需要引用v-has指令
<el-button @click='editClick' type="primary" v-has>编辑</el-button>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。