[Abp vNext微服务实践] - vue-element-admin登录二
简介:#
Vue Element Admin是基于vue、element ui开发的后台管理ui,abp vNext是abp新一代微服务框架。本篇将会介绍如何改造Vue Element Admin权限验证并接入abp vNext的微服务权限模块。上篇已经介绍过Vue Element Admin登录过程,并实现了假登录,本篇将介绍Vue Element Admin(后称Admin)实现登录权限验证。
Vue Element Admin权限验证代码分析#
Admin在permission.js实现了全局登录验证,主要代码如下:
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则直接进入首页。进入首页前会判断是否获取用户权限,如果没有则重新获取用户权限。主要改造在:
const { roles } = await store.dispatch('user/getPermissions', user.sub)
getPermissions代码如下:
getPermissions({ commit }, sub) { return new Promise((resolve, reject) => { var params = {} params.providerName = 'User' params.providerKey = sub axiosMethods.getPermissions('/api/abp/application-configuration', params) .then(response => { const data = {} data.roles = []
for(var role in response.auth.grantedPolicies){
data.roles.push(role)
}
if (!data.roles || data.roles.length <= 0) { reject('getInfo: roles must be a non-null array!') } commit('SET_ROLES', data.roles) resolve(data) }) }) }
代码分析:通过user的token信息请求/api/abp/application-configuration接口,获取权限后返回数组data。permission.js根据返回的roles动态挂载路由,此时权限改造就完成了,下面在权限测试页面进行测试。
修改权限测试页面路由配置如下:
登录后菜单如下: