首页 技术 正文
技术 2022年11月20日
0 收藏 850 点赞 3,601 浏览 14818 个字

1.权限的简单描述2.实例表结构及内容及POJO3.Shiro-pom.xml4.Shiro-web.xml5.Shiro-MyShiro-权限认证,登录认证层6.Shiro-applicationContext-shiro.xml7.HomeController三个JSP文件 

什么是权限呢?举个简单的例子:
我有一个论坛,注册的用户分为normal用户,manager用户。
对论坛的帖子的操作有这些:
添加,删除,更新,查看,回复
我们规定:
normal用户只能:添加,查看,回复
manager用户可以:删除,更新

normal,manager对应的是角色(role)
添加,删除,更新等对应的是权限(permission)

我们采用下面的逻辑创建权限表结构(不是绝对的,根据需要修改)

一个用户可以有多种角色(normal,manager,admin等等)
一个角色可以有多个用户(user1,user2,user3等等)
一个角色可以有多个权限(save,update,delete,query等等)
一个权限只属于一个角色(delete只属于manager角色)

我们创建四张表:
t_user用户表:设置了3个用户
——————————-
id + username   + password
—+—————-+———-
1  +   tom           +  000000
2  +   jack           +  000000
3  +   rose          +  000000
———————————
t_role角色表:设置3个角色
————–
id + rolename 
—+———-
1  + admin
2  + manager
3  + normal
————–
t_user_role用户角色表:tom是admin和normal角色,jack是manager和normal角色,rose是normal角色
———————
user_id  +  role_id
———–+———–
1            +     1
1            +     3
2            +     2
2            +     3
3            +     3
———————
t_permission权限表:admin角色可以删除,manager角色可以添加和更新,normal角色可以查看
———————————–
id  +  permissionname  +  role_id
—-+————————+———–
1   +   add                     +     2
2   +   del                       +    1
3   +   update                +     2
4   +   query                   +    3
———————————–

使用SHIRO的步骤:
1,导入jar
2,配置web.xml
3,建立dbRelm
4,在Spring中配置

pom.xml中配置如下:

Xml代码  

  1. <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  2. xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”>
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.hyx</groupId>
  5. <artifactId>springmvc</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>springmvc Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <dependencies>
  11. <dependency>
  12. <groupId>junit</groupId>
  13. <artifactId>junit</artifactId>
  14. <version>3.8.1</version>
  15. <scope>test</scope>
  16. </dependency>
  17. <!– SpringMVC核心jar –>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-webmvc</artifactId>
  21. <version>3.2.4.RELEASE</version>
  22. </dependency>
  23. <!– springmvc连接数据库需要的jar –>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-jdbc</artifactId>
  27. <version>3.2.4.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-orm</artifactId>
  32. <version>3.2.4.RELEASE</version>
  33. </dependency>
  34. <!– ************************************ –>
  35. <!– Hibernate相关jar –>
  36. <dependency>
  37. <groupId>org.hibernate</groupId>
  38. <artifactId>hibernate-core</artifactId>
  39. <version>4.2.5.Final</version>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.hibernate</groupId>
  43. <artifactId>hibernate-ehcache</artifactId>
  44. <version>4.2.5.Final</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>net.sf.ehcache</groupId>
  48. <artifactId>ehcache</artifactId>
  49. <version>2.7.2</version>
  50. </dependency>
  51. <dependency>
  52. <groupId>commons-dbcp</groupId>
  53. <artifactId>commons-dbcp</artifactId>
  54. <version>1.4</version>
  55. </dependency>
  56. <dependency>
  57. <groupId>mysql</groupId>
  58. <artifactId>mysql-connector-java</artifactId>
  59. <version>5.1.26</version>
  60. </dependency>
  61. <!– javax提供的annotation –>
  62. <dependency>
  63. <groupId>javax.inject</groupId>
  64. <artifactId>javax.inject</artifactId>
  65. <version>1</version>
  66. </dependency>
  67. <!– **************************** –>
  68. <!– hibernate验证 –>
  69. <dependency>
  70. <groupId>org.hibernate</groupId>
  71. <artifactId>hibernate-validator</artifactId>
  72. <version>5.0.1.Final</version>
  73. </dependency>
  74. <!– 用于对@ResponseBody注解的支持 –>
  75. <dependency>
  76. <groupId>org.codehaus.jackson</groupId>
  77. <artifactId>jackson-mapper-asl</artifactId>
  78. <version>1.9.13</version>
  79. </dependency>
  80. <!– 提供对c标签的支持 –>
  81. <dependency>
  82. <groupId>javax.servlet</groupId>
  83. <artifactId>jstl</artifactId>
  84. <version>1.2</version>
  85. </dependency>
  86. <!– servlet api –>
  87. <dependency>
  88. <groupId>javax.servlet</groupId>
  89. <artifactId>servlet-api</artifactId>
  90. <version>2.5</version>
  91. </dependency>
  92. <!–Apache Shiro所需的jar包–>
  93. <dependency>
  94. <groupId>org.apache.shiro</groupId>
  95. <artifactId>shiro-core</artifactId>
  96. <version>1.2.2</version>
  97. </dependency>
  98. <dependency>
  99. <groupId>org.apache.shiro</groupId>
  100. <artifactId>shiro-web</artifactId>
  101. <version>1.2.2</version>
  102. </dependency>
  103. <dependency>
  104. <groupId>org.apache.shiro</groupId>
  105. <artifactId>shiro-spring</artifactId>
  106. <version>1.2.2</version>
  107. </dependency>
  108. </dependencies>
  109. <build>
  110. <finalName>springmvc</finalName>
  111. <!– maven的jetty服务器插件 –>
  112. <plugins>
  113. <plugin>
  114. <groupId>org.mortbay.jetty</groupId>
  115. <artifactId>jetty-maven-plugin</artifactId>
  116. <configuration>
  117. <scanIntervalSeconds>10</scanIntervalSeconds>
  118. <webApp>
  119. <contextPath>/</contextPath>
  120. </webApp>
  121. <!– 修改jetty的默认端口 –>
  122. <connectors>
  123. <connector implementation=”org.eclipse.jetty.server.nio.SelectChannelConnector”>
  124. <port>80</port>
  125. <maxIdleTime>60000</maxIdleTime>
  126. </connector>
  127. </connectors>
  128. </configuration>
  129. </plugin>
  130. </plugins>
  131. </build>
  132. </project>

 web.xml中的配置:

Xml代码  

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <web-app version=”2.5″
  3. xmlns=”http://java.sun.com/xml/ns/javaee”
  4. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  5. xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
  7. <display-name>Archetype Created Web Application</display-name>
  8. <!– spring-orm-hibernate4的OpenSessionInViewFilter –>
  9. <filter>
  10. <filter-name>opensessioninview</filter-name>
  11. <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  12. </filter>
  13. <filter-mapping>
  14. <filter-name>opensessioninview</filter-name>
  15. <url-pattern>/*</url-pattern>
  16. </filter-mapping>
  17. <!– 配置springmvc servlet –>
  18. <servlet>
  19. <servlet-name>springmvc</servlet-name>
  20. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  21. <load-on-startup>1</load-on-startup>
  22. </servlet>
  23. <servlet-mapping>
  24. <servlet-name>springmvc</servlet-name>
  25. <!– / 表示所有的请求都要经过此serlvet –>
  26. <url-pattern>/</url-pattern>
  27. </servlet-mapping>
  28. <!– spring的监听器 –>
  29. <context-param>
  30. <param-name>contextConfigLocation</param-name>
  31. <param-value>classpath:applicationContext*.xml</param-value>
  32. </context-param>
  33. <listener>
  34. <listener-class>
  35. org.springframework.web.context.ContextLoaderListener
  36. </listener-class>
  37. </listener>
  38. <!– Shiro配置 –>
  39. <filter>
  40. <filter-name>shiroFilter</filter-name>
  41. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  42. </filter>
  43. <filter-mapping>
  44. <filter-name>shiroFilter</filter-name>
  45. <url-pattern>/*</url-pattern>
  46. </filter-mapping>
  47. </web-app>

Java代码  

  1. package com.cn.service;
  2. import java.util.List;
  3. import javax.inject.Inject;
  4. import org.apache.shiro.authc.AuthenticationException;
  5. import org.apache.shiro.authc.AuthenticationInfo;
  6. import org.apache.shiro.authc.AuthenticationToken;
  7. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  8. import org.apache.shiro.authc.UsernamePasswordToken;
  9. import org.apache.shiro.authz.AuthorizationInfo;
  10. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  11. import org.apache.shiro.realm.AuthorizingRealm;
  12. import org.apache.shiro.subject.PrincipalCollection;
  13. import org.springframework.stereotype.Service;
  14. import org.springframework.transaction.annotation.Transactional;
  15. import com.cn.pojo.Role;
  16. import com.cn.pojo.User;
  17. @Service
  18. @Transactional
  19. public class MyShiro extends AuthorizingRealm{
  20. @Inject
  21. private UserService userService;
  22. /**
  23. * 权限认证
  24. */
  25. @Override
  26. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  27. //获取登录时输入的用户名
  28. String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();
  29. //到数据库查是否有此对象
  30. User user=userService.findByName(loginName);
  31. if(user!=null){
  32. //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
  33. SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
  34. //用户的角色集合
  35. info.setRoles(user.getRolesName());
  36. //用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要
  37. List<Role> roleList=user.getRoleList();
  38. for (Role role : roleList) {
  39. info.addStringPermissions(role.getPermissionsName());
  40. }
  41. return info;
  42. }
  43. return null;
  44. }
  45. /**
  46. * 登录认证;
  47. */
  48. @Override
  49. protected AuthenticationInfo doGetAuthenticationInfo(
  50. AuthenticationToken authenticationToken) throws AuthenticationException {
  51. //UsernamePasswordToken对象用来存放提交的登录信息
  52. UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
  53. //查出是否有此用户
  54. User user=userService.findByName(token.getUsername());
  55. if(user!=null){
  56. //若存在,将此用户存放到登录认证info中
  57. return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
  58. }
  59. return null;
  60. }
  61. }

在spring的配置文件中配置,为了区别spring原配置和shiro我们将shiro的配置独立出来。

applicationContext-shiro.xml

Xml代码  

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  4. xmlns:aop=”http://www.springframework.org/schema/aop”
  5. xmlns:tx=”http://www.springframework.org/schema/tx”
  6. xmlns:context=”http://www.springframework.org/schema/context”
  7. xsi:schemaLocation=”
  8. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  11. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd”>
  12. <!– 配置权限管理器 –>
  13. <bean id=”securityManager” class=”org.apache.shiro.web.mgt.DefaultWebSecurityManager”>
  14. <!– ref对应我们写的realm  MyShiro –>
  15. <property name=”realm” ref=”myShiro”/>
  16. <!– 使用下面配置的缓存管理器 –>
  17. <property name=”cacheManager” ref=”cacheManager”/>
  18. </bean>
  19. <!– 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 –>
  20. <bean id=”shiroFilter” class=”org.apache.shiro.spring.web.ShiroFilterFactoryBean”>
  21. <!– 调用我们配置的权限管理器 –>
  22. <property name=”securityManager” ref=”securityManager”/>
  23. <!– 配置我们的登录请求地址 –>
  24. <property name=”loginUrl” value=”/login”/>
  25. <!– 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 –>
  26. <property name=”successUrl” value=”/user”/>
  27. <!– 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 –>
  28. <property name=”unauthorizedUrl” value=”/403″/>
  29. <!– 权限配置 –>
  30. <property name=”filterChainDefinitions”>
  31. <value>
  32. <!– anon表示此地址不需要任何权限即可访问 –>
  33. /static/**=anon
  34. <!– perms[user:query]表示访问此连接需要权限为user:query的用户 –>
  35. /user=perms[user:query]
  36. <!– roles[manager]表示访问此连接需要用户的角色为manager –>
  37. /user/add=roles[manager]
  38. /user/del/**=roles[admin]
  39. /user/edit/**=roles[manager]
  40. <!–所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login–>
  41. /** = authc
  42. </value>
  43. </property>
  44. </bean>
  45. <bean id=”cacheManager” class=”org.apache.shiro.cache.MemoryConstrainedCacheManager” />
  46. <bean id=”lifecycleBeanPostProcessor” class=”org.apache.shiro.spring.LifecycleBeanPostProcessor” />
  47. </beans>

 用于登录,登出,权限跳转的控制:

Java代码  

  1. package com.cn.controller;
  2. import javax.validation.Valid;
  3. import org.apache.shiro.SecurityUtils;
  4. import org.apache.shiro.authc.AuthenticationException;
  5. import org.apache.shiro.authc.UsernamePasswordToken;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.validation.BindingResult;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  12. import com.cn.pojo.User;
  13. @Controller
  14. public class HomeController {
  15. @RequestMapping(value=”/login”,method=RequestMethod.GET)
  16. public String loginForm(Model model){
  17. model.addAttribute(“user”, new User());
  18. return “/login”;
  19. }
  20. @RequestMapping(value=”/login”,method=RequestMethod.POST)
  21. public String login(@Valid User user,BindingResult bindingResult,RedirectAttributes redirectAttributes){
  22. try {
  23. if(bindingResult.hasErrors()){
  24. return “/login”;
  25. }
  26. //使用权限工具进行用户登录,登录成功后跳到shiro配置的successUrl中,与下面的return没什么关系!
  27. SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
  28. return “redirect:/user”;
  29. } catch (AuthenticationException e) {
  30. redirectAttributes.addFlashAttribute(“message”,”用户名或密码错误”);
  31. return “redirect:/login”;
  32. }
  33. }
  34. @RequestMapping(value=”/logout”,method=RequestMethod.GET)
  35. public String logout(RedirectAttributes redirectAttributes ){
  36. //使用权限管理工具进行用户的退出,跳出登录,给出提示信息
  37. SecurityUtils.getSubject().logout();
  38. redirectAttributes.addFlashAttribute(“message”, “您已安全退出”);
  39. return “redirect:/login”;
  40. }
  41. @RequestMapping(“/403”)
  42. public String unauthorizedRole(){
  43. return “/403”;
  44. }
  45. }

 三个主要的JSP:
login.jsp:

Html代码  

  1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  2. <%@ taglib prefix=”form” uri=”http://www.springframework.org/tags/form” %>
  3. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  4. <html>
  5. <head>
  6. <title>My JSP ‘MyJsp.jsp’ starting page</title>
  7. </head>
  8. <body>
  9. <h1>登录页面—-${message }</h1>
  10. <img alt=”” src=”/static/img/1.jpg”>
  11. <form:form action=”/login” commandName=”user” method=”post”>
  12. 用户名:<form:input path=”username”/> <form:errors path=”username” cssClass=”error”/> <br/>
  13. 密 &nbsp;&nbsp;码:<form:password path=”password”/> <form:errors path=”password” cssClass=”error” /> <br/>
  14. <form:button name=”button”>submit</form:button>
  15. </form:form>
  16. </body>
  17. </html>

user.jsp:

Html代码  

  1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
  2. <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
  3. <%@ taglib prefix=”shiro” uri=”http://shiro.apache.org/tags” %>
  4. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
  5. <html>
  6. <head>
  7. <title>用户列表</title>
  8. </head>
  9. <body>
  10. <h1>${message }</h1>
  11. <h1>用户列表–<a href=”/user/add”>添加用户</a>—<a href=”/logout”>退出登录</a>    </h1>
  12. <h2>权限列表</h2>
  13. <shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>
  14. <shiro:hasRole name=”manager”>manager角色登录显示此内容</shiro:hasRole>
  15. <shiro:hasRole name=”admin”>admin角色登录显示此内容</shiro:hasRole>
  16. <shiro:hasRole name=”normal”>normal角色登录显示此内容</shiro:hasRole>
  17. <shiro:hasAnyRoles name=”manager,admin”>**manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>
  18. <shiro:principal/>-显示当前登录用户名
  19. <shiro:hasPermission name=”add”>add权限用户显示此内容</shiro:hasPermission>
  20. <shiro:hasPermission name=”user:query”>query权限用户显示此内容<shiro:principal/></shiro:hasPermission>
  21. <shiro:lacksPermission name=”user:del”> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>
  22. <ul>
  23. <c:forEach items=”${userList }” var=”user”>
  24. <li>用户名:${user.username }—-密码:${user.password }—-<a href=”/user/edit/${user.id}”>修改用户</a>—-<a href=”javascript:;” class=”del” ref=”${user.id }”>删除用户</a></li>
  25. </c:forEach>
  26. </ul>
  27. <img alt=”” src=”/static/img/1.jpg”>
  28. <script type=”text/javascript” src=”http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js”></script>
  29. <script>
  30. $(function(){
  31. $(“.del”).click(function(){
  32. var id=$(this).attr(“ref”);
  33. $.ajax({
  34. type:”delete”,
  35. url:”/user/del/”+id,
  36. success:function(e){
  37. }
  38. });
  39. });
  40. });
  41. </script>
  42. </body>
  43. </html>

403.jsp:

Html代码  

    1. <%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
    2. <%@ taglib prefix=”form” uri=”http://www.springframework.org/tags/form” %>
    3. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
    4. <html>
    5. <head>
    6. <title>权限错误</title>
    7. </head>
    8. <body>
    9. <h1>对不起,您没有权限请求此连接!</h1>
    10. <img alt=”” src=”/static/img/1.jpg”>
    11. </body>
    12. </html>
    13. 框架/平台构成:
      Maven+Springmvc + Mybatis + Shiro(权限)+ Tiles(模板) +ActiveMQ(消息队列) + Rest(服务) + WebService(服务)+ EHcache(缓存) + Quartz(定时调度)+ Html5(支持PC、IOS、Android)

      用户权限系统:
      组织结构:角色、用户、用户组、组织机构;权限点:页面、方法、按钮、数据权限、分级授权

      项目管理新体验:
      快速出原型系统、组件树、版本控制、模块移植、协同开发、实时监控、发布管理

      可持续集成:
      所有组件可移植、可定制、可扩充,开发成果不断积累,形成可持续发展的良性循环

      支持平台平台: 
      Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix

      服务器容器:
      Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,030
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859