系统按钮权限使用
按钮权限概述
在后台菜单管理中给指定菜单添加 按钮节点,需要指定 权限标志。
💡权限标志命名
按钮权限标志通常采用模块名_操作名的命名方式,例如:sys_file_add、sys_file_del、sys_file_edit
对于扩展菜单(非增删改查),需要使用 vuex 保存用户的权限信息,然后通过 v-auth 指令判断是否有权限,如果有权限就渲染对应的 DOM 元素,例如:ext_btn。
前端控制
我们以用户管理页面来讲解。
// 按钮 v-if 使用
<el-table-column align="center" label="操作">
<template slot-scope="scope">
<el-button
v-auth="'ext_btn'"
size="small"
type="success"
@click="handleUpdate(scope.row)"
>扩展
</el-button>
</template>
</el-table-column>
后端权限控制
只需要在接口增加注解:
@PreAuthorize("@pms.hasPermission('XXX')")
实现原理
通过获取用户菜单列表,和请求的地址、请求方法对比判断是否有权限。
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
boolean hasPermission = false;
if (principal != null) {
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
return hasPermission;
}
Set<MenuVo> urls = new HashSet<>();
for (SimpleGrantedAuthority authority : grantedAuthorityList) {
urls.addAll(menuService.findMenuByRole(authority.getAuthority()));
}
for (MenuVo menu : urls) {
if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), request.getRequestURI())
&& request.getMethod().equalsIgnoreCase(menu.getMethod())) {
hasPermission = true;
break;
}
}
}
return hasPermission;
}