用Shiro配置菜单url 替代Permission的范例

Shiro的权限可以用role,permission,是否登录等等方式限定,详情可以参考

https://blog.****.net/howard789/article/details/83305478

但是这样管理大型项目的时候会很混乱,因为太复杂了

所以另一个思路,是用菜单URL作为permission来管理,每一个用户分配其角色(可以有多个角色),这个系统要求必须登录才能使用,如果是对外的公开项目就不合适,shiro一般也是用在需要控制权限的项目. 每个角色分配其可以访问的url,

所以当一个用户登录的时候,他会有可以访问的url的清单,这样我们就可以利用动态生成菜单和在页面上配置的方式

让其只能看见自己可以访问的菜单,以下例子,登录后全部有3个menu,hao的身份是admin,可以看到全部url,

yiqian是guest,只能看到最后一个url,用户登录的时候只能看到他有权限的菜单,只要能看到的菜单或功能,都是有权限访问的

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
    <meta charset="UTF-8"/>

    <title>Insert title here</title>
    <script src="/static/js/jquery-1.11.0.js" type="text/javascript"></script>
    <script src="/static/js/login.js" type="text/javascript"></script>

</head>
<body>

<a href="/login">login</a><br><br>

<shiro:hasPermission name="menu1">
    <a href="/menu1">go Menu1</a><br><br>
</shiro:hasPermission>

<shiro:hasPermission name="menu2">
    <a href="/menu2">go Menu2</a><br><br>
</shiro:hasPermission>

<shiro:hasPermission name="menu3">
    <a href="/menu3">go Menu3</a><br><br>
</shiro:hasPermission>


<p><input type="button" onclick="logoutJs()" value="logout" id="ajaxLogout"/></p>

</body>
</html>

用hao(role为admin)登录后的页面

用Shiro配置菜单url 替代Permission的范例

 

用yiqian(role为quest)登录后的页面

用Shiro配置菜单url 替代Permission的范例

核心就是把url作为permission,如果要下载完整的代码,可以在这里下载

https://download.****.net/download/howard789/11072718

项目用到spring-boot和mybatis。需要在test数据库里运行代码里的sql脚本,默认登录用户hao或yiqian,密码都是123456