Vue2实战:基于前端路由与API的权限管理系统设计与实现

在当前的企业级应用开发中,权限管理一直是核心且复杂的环节。如何有效地控制不同角色的用户访问不同的资源和接口,是确保系统安全性和可用性的关键。本文将深入探讨基于Vue2前端框架和后端API的权限管理系统设计与实现,涵盖前端路由权限、菜单权限、按钮权限以及后端接口权限的全方位控制。
一、项目背景与需求分析
在多数企业管理系统中,权限管理通常涉及以下几个方面:
路由权限
:不同角色的用户访问不同的页面。
菜单权限
:不同角色的用户看到不同的菜单项。
按钮权限
:不同角色的用户操作不同的按钮。
接口权限
:不同角色的用户调用不同的后端接口。
基于这些需求,我们选择Vue2作为前端框架,结合Element UI进行界面设计,后端则采用Spring Boot和Shiro进行权限控制。
二、前端设计与实现
1. 项目结构
首先,我们使用Vue CLI创建一个新的Vue2项目,并引入Element UI。项目结构如下:
src/
|– api/ # API接口模块
|– components/ # 公共组件
|– views/ # 页面组件
|– router/ # 路由配置
|– store/ # 状态管理
|– utils/ # 工具类
|– App.vue
|– main.js
2. 路由权限控制
在
router/index.js
中,我们定义全局前置守卫,根据用户的角色动态加载路由:
import Vue from ‘vue’
import Router from ‘vue-router’
import { getRoleRoutes } from ‘@/api/role’

Vue.use(Router)

const router = new Router({
routes: [
{
path: ‘/login’,
component: () => import(‘@/views/Login’)
},
{
path: ‘/’,
component: () => import(‘@/views/Layout’),
children: []
}
]
})

router.beforeEach((to, from, next) => {
const role = localStorage.getItem(‘role’)
if (!role && to.path !== ‘/login’) {
next(‘/login’)
} else {
if (to.path === ‘/login’) {
next()
} else {
getRoleRoutes(role).then(res => {
const routes = res.data
router.addRoutes(routes)
next({ …to, replace: true })
})
}
}
})

export default router
3. 菜单与按钮权限控制
在
views/Layout.vue
中,我们根据用户的角色动态生成菜单:


按钮权限则通过
v-if
指令动态控制:
添加
删除


三、后端设计与实现
1. Spring Boot与Shiro集成
在后端,我们使用Spring Boot框架,集成Shiro进行权限控制。首先,添加依赖:

org.apache.shiro
shiro-spring-boot-starter
1.7.1

2. 用户认证与授权
在
ShiroConfig
类中配置Shiro:
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl(“/login”);
shiroFilter.setUnauthorizedUrl(“/unauthorized”);

Map filterMap = new LinkedHashMap<>();
filterMap.put(“/login”, “anon”);
filterMap.put(“/api/**”, “authc”);
shiroFilter.setFilterChainDefinitionMap(filterMap);

return shiroFilter;
}

@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myRealm());
return securityManager;
}

@Bean
public MyRealm myRealm() {
return new MyRealm();
}
}
在
MyRealm
类中实现用户认证与授权:
public class MyRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException(“用户不存在”);
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
User user = (User) principals.getPrimaryPrincipal();
List roles = roleService.getRolesByUserId(user.getId());
List permissions = permissionService.getPermissionsByUserId(user.getId());
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roles);
authorizationInfo.addStringPermissions(permissions);
return authorizationInfo;
}
}
3. API接口权限控制
在Controller层,使用
@RequiresPermissions
注解控制接口访问权限:
@RestController
@RequestMapping(“/api/user”)
public class UserController {
@RequiresPermissions(“user:add”)
@PostMapping(“/add”)
public ResponseEntity addUser(@RequestBody User user) {
userService.addUser(user);
return ResponseEntity.ok(“用户添加成功”);
}

@RequiresPermissions(“user:delete”)
@DeleteMapping(“/delete/{id}”)
public ResponseEntity deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.ok(“用户删除成功”);
}
}
四、防止安全漏洞
1. 双重认证校验
在用户登录时,除了校验用户名和密码,还需生成并校验Token:
@PostMapping(“/login”)
public ResponseEntity login(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new AuthToken(token));
}
2. 防止水平越权
在获取用户信息时,通过Token校验用户身份的唯一性,确保A用户不能操作B用户的个人信息:
@GetMapping(“/user/{id}”)
public ResponseEntity getUserInfo(@PathVariable Long id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User currentUser = (User) authentication.getPrincipal();
if (!currentUser.getId().equals(id)) {
throw new AccessDeniedException(“无权访问”);
}
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
3. 防止垂直越权
确保低权限用户不能越权操作高权限用户的权限:
@RequiresRoles(“ADMIN”)
@PostMapping(“/role/assign”)
public ResponseEntity assignRole(@RequestBody RoleAssignRequest request) {
roleService.assignRole(request.getUserId(), request.getRoleId());
return ResponseEntity.ok(“角色分配成功”);
}
五、整体设计思路
前端通过Vue-Router控制路由、菜单、按钮和权限的基础数据和展示控制
,后端提供角色和路由、菜单、按钮的配置数据,然后过滤前端维护的基础数据从而实现路由、菜单、按钮的权限控制。
后端通过Shiro一方面实现登录控制,另一方面基于配置数据基础上实现接口权限控制
。
基于基础的登录权限控制功能上,可基于iview-admin自主定制企业管理功能模块
。
六、FAQ
跨域问题
:由于是前后端分离项目,应避免跨域问题,否则前端调用后端接口,无法携带Cookie实现接口权限控制功能。可通过配置CORS解决。
七、源码参考地址
前端:zwxu/FrontendTemplate
后端:zwxu/BackendTemplate
通过本文的详细讲解,希望能为你在开发基于Vue2的前端权限管理系统时提供有力的参考和指导。权限管理虽复杂,但只要理清思路,合理设计,便能构建出安全、高效的企业级应用。