Apache Shiro 授权例子

太过爱你忘了你带给我的痛 2022-09-20 15:06 177阅读 0赞

概述

在本例中使用Apache Shiro进行授权控制,基于事先定义好的角色控制用户的操作权限。

基于Apache Shiro 提供的标签库,在JSP页面上根据用户的授权状态来控制不同的操作行为。

业务逻辑

定义两种角色:administrator,common。

administrator代表管理员,可查看,修改,删除用户;

common代表普通用户,可查看用户,只能修改自己,不能删除用户。

数据准备

创建三个表

  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. create table roles(
  12. id int NOT NULL,
  13. name varchar(20),
  14. PRIMARY KEY (id)
  15. );
  16. --用户角色关系表
  17. create table user_to_role(
  18. user_id int NOT NULL,
  19. role_id int NOT NULL,
  20. PRIMARY KEY (user_id, role_id)
  21. );

初始化数据

  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. insert into roles(id,name) values(1,'administrator');
  6. insert into roles(id,name) values(2,'common');
  7. insert into user_to_role(user_id,role_id) values(1,1);
  8. insert into user_to_role(user_id,role_id) values(2,2);
  9. insert into user_to_role(user_id,role_id) values(3,2);
  10. insert into user_to_role(user_id,role_id) values(4,2);

工程代码

重构抽象类AuthorizingRealm的授权方法

  1. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  2. String userName = (String) principals.fromRealm(getName()).iterator().next();
  3. //根据用户名查找拥有的角色
  4. List<Roles> roles = userService.getUserRoles(userName);
  5. if (roles != null) {
  6. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  7. for (Roles role : roles) {
  8. info.addRole(role.getName());
  9. }
  10. return info;
  11. } else {
  12. return null;
  13. }
  14. }

展现用户信息列表Controller

  1. @Controller
  2. public class MainController {
  3. private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class);
  4. @Resource(name = "userService")
  5. private UserService userService;
  6. @RequestMapping(value = "/main.do")
  7. public String mainPage(HttpServletRequest request, ModelMap model) {
  8. HttpSession session = request.getSession(true);
  9. Subject user = SecurityUtils.getSubject();
  10. String userID = (String) user.getPrincipal();
  11. LOGGER.info(userID);
  12. session.setAttribute("USERNAME", userID);
  13. List<Users> users = userService.getAllUsers();
  14. model.addAttribute("users", users);
  15. return "main";
  16. }
  17. }

用户信息列表JSP页面

  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. </p>
  29. <form:form>
  30. <table id="contentTable" align=center>
  31. <thead>
  32. <tr>
  33. <th>序号</th>
  34. <th>登录名</th>
  35. <th>姓名</th>
  36. <th>性别</th>
  37. <shiro:hasAnyRoles name="administrator,common">
  38. <th>操作</th>
  39. </shiro:hasAnyRoles>
  40. </tr>
  41. </thead>
  42. <tbody>
  43. <c:forEach items="${users}" var="user" varStatus="status">
  44. <tr>
  45. <td>${ status.index + 1}</td>
  46. <td>${user.name}</td>
  47. <td>${user.realName}</td>
  48. <td><c:if test="${user.sex=='1'}"></c:if>
  49. <c:if test="${user.sex=='0'}"></c:if></td>
  50. <shiro:hasRole name="administrator">
  51. <td><a href="#"
  52. οnclick="return confirmx('确认要修改该用户吗?')">修改</a> <a
  53. href="#" οnclick="return confirmx('确认要删除该用户吗?')">删除</a></td>
  54. </shiro:hasRole>
  55. <shiro:hasRole name="common">
  56. <c:if test="${user.name==currentUser}">
  57. <td><a href="#"
  58. οnclick="return confirmx('确认要修改该用户吗?')">修改</a></td>
  59. </c:if>
  60. </shiro:hasRole>
  61. </tr>
  62. </c:forEach>
  63. </tbody>
  64. </table>
  65. </form:form>
  66. </body>
  67. </html>

想使用Shiro标签首先引用标签库<%@ taglib prefix=”shiro” uri=”http://shiro.apache.org/tags"%>

本例中用到了,shiro:hasAnyRoles,shiro:hasRole这几个标签

效果

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

SouthEast

![Image 1][]

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

![Image 1][]

SouthEast 1

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,177人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Apache Shiro 授权概念

    授权即是访问控制,是对资源访问管理过程。它将判断用户在应用程序中是否对资源有相应的访问权限。比如:判断一个用户有查看页面的权限,编辑数据的权限,拥有某一按钮的权限,以及是否拥有

    相关 Apache Shiro 授权概念

    授权即是访问控制,是对资源访问管理过程。它将判断用户在应用程序中是否对资源有相应的访问权限。比如:判断一个用户有查看页面的权限,编辑数据的权限,拥有某一按钮的权限,以及是否拥有

    相关 Apache Shiro授权

    主要概念 授权:又叫做访问控制,即在应用中控制谁访问哪些资源(如访问页面/编辑数据/页面操作等)。在授权中需了解的几个关键对象:主体(Subject)、资源(Resour...