Vue Element Admin是基於vue、element ui開發的後臺管理ui,abp vNext是abp新一代微服務框架。本篇將會介紹如何改造Vue Element Admin權限驗證並接入abp vNext的微服務權限模塊。上篇已經介紹過Vue Element Admin登陸過程,並實現了假登陸,本篇將介紹Vue Element Admin(後稱Admin)實現登陸權限驗證。vue
Admin在permission.js實現了全局登陸驗證,主要代碼以下:ios
const hasToken = getToken() if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() } else { // determine whether the user has obtained his permission roles through getInfo const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (hasRoles) { next() } else { try { // get user info var user = await store.dispatch('user/getInfo') // note: roles must be a object array! such as: ['admin'] or ,['developer','editor'] const { roles } = await store.dispatch('user/getPermissions', user.sub) // generate accessible routes map based on roles const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // dynamically add accessible routes router.addRoutes(accessRoutes) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next() } else { // other pages that do not have permission to access are redirected to the login page. next(`/login?redirect=${to.path}`) NProgress.done() } }
分析代碼得知在訪問Admin時會首先獲取token,若是token不存在會直接跳轉登陸,若是token存在會判斷當前路由,若是路由指向login則直接進入首頁。進入首頁前會判斷是否獲取用戶權限,若是沒有則從新獲取用戶權限。主要改造在:axios
getPermissions({ commit }, sub) { return new Promise((resolve, reject) => { var params = {} params.providerName = 'User' params.providerKey = sub axiosMethods.getPermissions('/api/abp/permissions', params) .then(response => { const data = {} data.roles = [] response.groups.forEach(element => { element.permissions.forEach(item => { data.roles.push(item.name) }) }) if (!data.roles || data.roles.length <= 0) { reject('getInfo: roles must be a non-null array!') } commit('SET_ROLES', data.roles) resolve(data) }) }) }
代碼分析:經過user的sub信息請求/api/abp/permissions接口,獲取權限後返回數組data。permission.js根據返回的roles動態掛載路由,此時權限改造就完成了,下面在權限測試頁面進行測試。api
修改權限測試頁面路由配置以下:數組
登陸、權限驗證改造完畢後在菜單中加入系統管理---用戶、角色管理後就能夠開始業務開發了。框架