Vue中實現(xiàn)權限管理詳解
權限管理分類
前端權限歸根結(jié)底是請求的發(fā)起權,一般有兩種觸發(fā)方式
- 頁面加載觸發(fā)(頁面刷新、頁面跳轉(zhuǎn))
- 用戶事件觸發(fā)(點擊按鈕等操作)
在前端需要達到的權限目的:
- 路由方面,用戶登錄有只能看到自己有權訪問的導航菜單,也只能訪問自己有權訪問的路由地址
- 視圖方面,用戶只能看到自己有權看到的資源和有權操作的控件
- 接口方面,若是路由、視圖等都配置失誤,忘記加權限,則可以在發(fā)起請求的時候攔截越權請求
因此前端權限管理可分為四類:
- 接口權限
- 路由權限
- 菜單權限
- 視圖權限(按鈕權限)
接口權限
Vue項目中廣泛使用axios
進行前后端交互,并配合后端返回的jwt
進行接口的權限控制
用戶在登錄后獲取token
,在axios
的請求攔截器中添加token
,若是token
無效或者已過期,則進行相應的處理。
axios.interceptors.request.use(config => { config.headers['token'] = cookie.get('token') return config })
路由權限
方案一
初始化時即掛載全部路由,并且在路由中的元信息(meta
標記相應的權限信息,通過設置全局路由守衛(wèi),每次路由跳轉(zhuǎn)前做校驗。
const routerMap = [ { path: '/permission', component: Layout, redirect: '/permission/index', alwaysShow: true, // will always show the root menu 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: 'pagePermission', roles: ['admin'] // or you can only set roles in sub nav } }, { path: 'directive', component: () => import('@/views/permission/directive'), name: 'directivePermission', meta: { title: 'directivePermission' // if do not set roles, means: this page does not require permission } }] }]
這種方式存在以下四種缺點:
- 加載所有的路由,如果路由很多,而用戶并不是所有的路由都有權限訪問,對性能會有影響。
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做權限判斷。
- 菜單信息寫死在前端,要改個顯示文字或權限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
方案二
初始化的時候先掛載不需要權限控制的路由,比如登錄頁,404等錯誤頁。如果用戶通過URL進行強制訪問,則會直接進入404,相當于從源頭上做了控制。。
登錄后,獲取用戶的權限信息,然后篩選有權限訪問的路由,在全局路由守衛(wèi)里進行調(diào)用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 NProgress.configure({ showSpinner: false })// NProgress Configuration // permission judge function function hasPermission(roles, permissionRoles) { 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, from, next) => { NProgress.start() // start progress bar if (getToken()) { // determine if there has token /* has token*/ if (to.path === '/login') { next({ path: '/' }) NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { if (store.getters.roles.length === 0) { // 判斷當前用戶是否已拉取完user_info信息 store.dispatch('GetUserInfo').then(res => { // 拉取user_info const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop'] store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權限生成可訪問的路由表 router.addRoutes(store.getters.addRouters) // 動態(tài)添加可訪問路由表 next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,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 { // 沒有動態(tài)改變權限的需求可直接next() 刪除下方權限判斷 ↓ if (hasPermission(store.getters.roles, to.meta.roles)) { next()// } else { next({ path: '/401', replace: true, query: { noGoBack: true }}) } // 可刪 ↑ } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next() } else { next('/login') // 否則全部重定向到登錄頁 NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it } } }) router.afterEach(() => { NProgress.done() // finish progress bar })
按需掛載,路由就需要知道用戶的路由權限,也就是在用戶登錄進來的時候就要知道當前用戶擁有哪些路由權限
這種方式也存在了以下的缺點:
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
- 菜單信息寫死在前端,要改個顯示文字或權限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
菜單權限
菜單權限可以理解成將頁面與路由進行解耦
方案一
前端定義路由,后端返回菜單
前端定義路由信息
{ name: "login", path: "/login", component: () => import("@/pages/Login.vue") }
name
字段不能為空,需要根據(jù)此字段與后端返回菜單做關聯(lián),后端返回的菜單信息中必須要有name
對應的字段,并且做唯一性校驗
全局路由守衛(wèi)
function hasPermission(router, accessMenu) { if (whiteList.indexOf(router.path) !== -1) { return true; } let menu = Util.getMenuByName(router.name, accessMenu); if (menu.name) { return true; } return false; } Router.beforeEach(async (to, from, next) => { if (getToken()) { let 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 { //Util.toDefaultPage([...routers], to.name, router, next); 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, routes, next); } else { next({ path: '/403',replace:true }) } } } } else { if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next() } else { next('/login') } } let menu = Util.getMenuByName(to.name, store.getters.accessMenu); Util.title(menu.title); }); Router.afterEach((to) => { window.scrollTo(0, 0); });
每次路由跳轉(zhuǎn)的時候都要判斷權限,這里的判斷也很簡單,因為菜單的name
與路由的name
是一一對應的,而后端返回的菜單就已經(jīng)是經(jīng)過權限過濾的
如果根據(jù)路由name
找不到對應的菜單,就表示用戶有沒權限訪問
如果路由很多,可以在應用初始化的時候,只掛載不需要權限控制的路由。取得后端返回的菜單后,根據(jù)菜單與路由的對應關系,篩選出可訪問的路由,通過addRoutes
動態(tài)掛載
方案二
路由和菜單全由后端返回
前端統(tǒng)一定義組件
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動態(tài)掛載之間,需要將數(shù)據(jù)處理一下,將component字段換為真正的組件
此方案要求前后端配合度極高
視圖權限
方案一
通過v-if
控制按鈕的顯示或隱藏
方案二
通過自定義指令進行按鈕權限的判斷
首先配置路由
{ 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 Vue from 'vue' /**權限指令**/ const has = Vue.directive('has', { bind: function (el, binding, vnode) { // 獲取頁面按鈕權限 let btnPermissionsArr = []; if(binding.value){ // 如果指令傳值,獲取指令參數(shù),根據(jù)指令參數(shù)和當前登錄人按鈕權限做比較。 btnPermissionsArr = Array.of(binding.value); }else{ // 否則獲取路由中的參數(shù),根據(jù)路由的btnPermissionsArr和當前登錄人按鈕權限做比較。 btnPermissionsArr = vnode.context.$route.meta.btnPermissions; } if (!Vue.prototype.$_has(btnPermissionsArr)) { el.parentNode.removeChild(el); } } }); // 權限檢查方法 Vue.prototype.$_has = function (value) { 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}
在使用的按鈕中只需要引用v-has指令
<el-button @click='editClick' type="primary" v-has>編輯</el-button>
到此這篇關于Vue中實現(xiàn)權限管理詳解的文章就介紹到這了,更多相關Vue權限管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Create?vite理解Vite項目創(chuàng)建流程及代碼實現(xiàn)
這篇文章主要為大家介紹了Create?vite理解Vite項目創(chuàng)建流程及代碼實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10在vue-cli創(chuàng)建的項目中使用sass操作
這篇文章主要介紹了在vue-cli創(chuàng)建的項目中使用sass操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08vue3實現(xiàn)動態(tài)側(cè)邊菜單欄的幾種方式簡單總結(jié)
在做開發(fā)中都會遇到的需求,每個用戶的權限是不一樣的,那他可以訪問的頁面(路由)可以操作的菜單選項是不一樣的,如果由后端控制,我們前端需要去實現(xiàn)動態(tài)路由,動態(tài)渲染側(cè)邊菜單欄,這篇文章主要給大家介紹了關于vue3實現(xiàn)動態(tài)側(cè)邊菜單欄的幾種方式,需要的朋友可以參考下2024-02-02proxy代理不生效以及vue?config.js不生效解決方法
在開發(fā)Vue項目過程中,使用了Proxy代理進行數(shù)據(jù)劫持,但是在實際運行過程中發(fā)現(xiàn)代理并沒有生效,也就是說數(shù)據(jù)并沒有被劫持,這篇文章主要給大家介紹了關于proxy代理不生效以及vue?config.js不生效解決方法的相關資料,需要的朋友可以參考下2023-11-11詳解Vue自定義指令如何實現(xiàn)處理圖片加載失敗的碎圖
這篇文章主要介紹了詳解Vue自定義指令如何實現(xiàn)處理圖片加載失敗的碎圖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02