Apache Shiro 授权例子


标签: apacheshiro
  6330人阅读  评论(2)  收藏  举报
  分类:

目录(?)[+]

概述

在本例中使用Apache Shiro进行授权控制,基于事先定义好的角色控制用户的操作权限。
基于Apache Shiro 提供的标签库,在JSP页面上根据用户的授权状态来控制不同的操作行为。

业务逻辑

定义两种角色:administrator,common。
administrator代表管理员,可查看,修改,删除用户;
common代表普通用户,可查看用户,只能修改自己,不能删除用户。

数据准备

创建三个表
[sql]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. --用户信息表  
  2. create table users(  
  3.     id int NOT NULL,  
  4.     name varchar(20),  
  5.     passwd varchar(20),  
  6.     real_name varchar(20),  
  7.     sex char(1),  
  8.     PRIMARY KEY (id)  
  9. );  
  10.   
  11. --角色信息表  
  12. create table roles(  
  13.     id int NOT NULL,  
  14.     name varchar(20),  
  15.     PRIMARY KEY (id)  
  16. );  
  17.   
  18. --用户角色关系表  
  19. create table user_to_role(  
  20.     user_id int NOT NULL,  
  21.     role_id int NOT NULL,  
  22.     PRIMARY KEY (user_id, role_id)  
  23. );  

初始化数据
[sql]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. insert into users(id,name,passwd,real_name,sex) values(1,'admin','admin','管理员','1');  
  2. insert into users(id,name,passwd,real_name,sex) values(2,'Peter','Peter','彼得','1');  
  3. insert into users(id,name,passwd,real_name,sex) values(3,'Tom','Tom','汤姆','1');  
  4. insert into users(id,name,passwd,real_name,sex) values(4,'Sophie','Sophie','苏菲','0');  
  5.   
  6. insert into roles(id,namevalues(1,'administrator');  
  7. insert into roles(id,namevalues(2,'common');  
  8.   
  9. insert into user_to_role(user_id,role_id) values(1,1);  
  10. insert into user_to_role(user_id,role_id) values(2,2);  
  11. insert into user_to_role(user_id,role_id) values(3,2);  
  12. insert into user_to_role(user_id,role_id) values(4,2);  


工程代码

重构抽象类AuthorizingRealm的授权方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  2.         String userName = (String) principals.fromRealm(getName()).iterator().next();  
  3.   
  4.         //根据用户名查找拥有的角色  
  5.         List<Roles> roles = userService.getUserRoles(userName);  
  6.         if (roles != null) {  
  7.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  8.   
  9.             for (Roles role : roles) {  
  10.                 info.addRole(role.getName());  
  11.             }  
  12.   
  13.             return info;  
  14.         } else {  
  15.             return null;  
  16.         }  
  17.     }  

展现用户信息列表Controller
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Controller  
  2. public class MainController {  
  3.     private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);  
  4.   
  5.     @Resource(name = "userService")  
  6.     private UserService userService;  
  7.   
  8.     @RequestMapping(value = "/main.do")  
  9.     public String mainPage(HttpServletRequest request, ModelMap model) {  
  10.         HttpSession session = request.getSession(true);  
  11.         Subject user = SecurityUtils.getSubject();  
  12.         String userID = (String) user.getPrincipal();  
  13.         LOGGER.info(userID);  
  14.         session.setAttribute("USERNAME", userID);  
  15.         List<Users> users = userService.getAllUsers();  
  16.   
  17.         model.addAttribute("users", users);  
  18.         return "main";  
  19.   
  20.     }  
  21. }  

用户信息列表JSP页面
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  5. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  6. <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>  
  7. <%  
  8.     String userName = (String) session.getAttribute("USERNAME");  
  9.     pageContext.setAttribute("currentUser", org.apache.shiro.SecurityUtils.getSubject().getPrincipal()  
  10.             .toString());  
  11. %>  
  12. <html>  
  13. <head>  
  14. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  15. <title>Login Success</title>  
  16. <script type="text/javascript">  
  17. function confirmx(mess){  
  18.     alert(mess);  
  19. }  
  20. </script>  
  21. </head>  
  22. <body bgcolor="#f3f3f3">  
  23.     <p align=center>  
  24.         <shiro:guest>Hi Guest</shiro:guest>  
  25.         <shiro:user>  
  26.             <shiro:principal />:你好,欢迎您</shiro:user>  
  27.         !  
  28.   
  29.     </p>  
  30.   
  31.     <form:form>  
  32.         <table id="contentTable" align=center>  
  33.             <thead>  
  34.                 <tr>  
  35.                     <th>序号</th>  
  36.                     <th>登录名</th>  
  37.                     <th>姓名</th>  
  38.                     <th>性别</th>  
  39.                     <shiro:hasAnyRoles name="administrator,common">  
  40.                         <th>操作</th>  
  41.                     </shiro:hasAnyRoles>  
  42.                 </tr>  
  43.             </thead>  
  44.             <tbody>  
  45.                 <c:forEach items="${users}" var="user" varStatus="status">  
  46.                     <tr>  
  47.                         <td>${ status.index + 1}</td>  
  48.                         <td>${user.name}</td>  
  49.                         <td>${user.realName}</td>  
  50.                         <td><c:if test="${user.sex=='1'}"></c:if>  
  51.                             <c:if test="${user.sex=='0'}"></c:if></td>  
  52.                         <shiro:hasRole name="administrator">  
  53.                             <td><a href="#"  
  54.                                 onclick="return confirmx('确认要修改该用户吗?')">修改</a> <a  
  55.                                 href="#" onclick="return confirmx('确认要删除该用户吗?')">删除</a></td>  
  56.                         </shiro:hasRole>  
  57.                         <shiro:hasRole name="common">  
  58.                             <c:if test="${user.name==currentUser}">  
  59.                                 <td><a href="#"  
  60.                                     onclick="return confirmx('确认要修改该用户吗?')">修改</a></td>  
  61.                             </c:if>  
  62.                         </shiro:hasRole>  
  63.                     </tr>  
  64.                 </c:forEach>  
  65.             </tbody>  
  66.         </table>  
  67.     </form:form>  
  68.   
  69. </body>  
  70. </html>  

想使用Shiro标签首先引用标签库<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
本例中用到了<shiro:user>,<shiro:principal />,shiro:hasAnyRoles,shiro:hasRole这几个标签

效果

使用admin/admin登录,页面如下:


使用Peter/Peter登录,页面如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值