1、向spring项目中添加shiro相关的依赖

  1. <dependency>
  2. <groupId>commons-logging</groupId>
  3. <artifactId>commons-logging</artifactId>
  4. <version>1.1.3</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-collections</groupId>
  8. <artifactId>commons-collections</artifactId>
  9. <version>3.2.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.shiro</groupId>
  13. <artifactId>shiro-core</artifactId>
  14. <version>1.2.2</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.shiro</groupId>
  18. <artifactId>shiro-web</artifactId>
  19. <version>1.2.2</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>net.sf.ehcache</groupId>
  23. <artifactId>ehcache-core</artifactId>
  24. <version>2.6.8</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.apache.shiro</groupId>
  28. <artifactId>shiro-ehcache</artifactId>
  29. <version>1.2.2</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.apache.shiro</groupId>
  33. <artifactId>shiro-quartz</artifactId>
  34. <version>1.2.2</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.apache.shiro</groupId>
  38. <artifactId>shiro-spring</artifactId>
  39. <version>1.2.2</version>
  40. </dependency>

2、在web.xml配置ShiroFilter

  1. <!-- shiro过虑器,DelegatingFilterProx会从spring容器中找shiroFilter -->
  2. <filter>
  3. <filter-name>shiroFilter</filter-name>
  4. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  5. <init-param>
  6. <param-name>targetFilterLifecycle</param-name>
  7. <param-value>true</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>shiroFilter</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>

3、建立一个 spring 的配置文件 spring-shiro.xml

  a、使用 import 标签把此文件引入为spring的配置文件

  1. <import resource="classpath:spring-shiro.xml"></import>

  b、配置spring-shiro.xml文件

  1. <!-- shiro 拦截器配置 -->
  2. <!-- ShiroFilter 名字必须要和web.xml中配置的名字一致 -->
  3. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  4. <property name="securityManager" ref="securityManager"/>
  5. <property name="loginUrl" value="/login"/>
  6. <property name="unauthorizedUrl" value="/nopermission.jsp"/>
  7. <!-- filterChainDefinitions 相当于.ini文件中的[urls] -->
  8. <property name="filterChainDefinitions">
  9. <value>
  10. /logout=logout
  11. /**=authc
  12. </value>
  13. </property>
  14. </bean>
  15. <!--shiro权限异常处理 -->
  16. <!-- 上面对“/nopermission.jsp”的配置不会生效,因为 spring 默认会抛出异常到页面;需要添加下面这个配置才可以生效-->
  17. <!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常页名作为值 -->
  18. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  19. <property name="exceptionMappings">
  20. <props>
  21. <prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/nopermission.jsp</prop>
  22. </props>
  23. </property>
  24. </bean>
  25.  
  26. <!-- 配置安全管理器SecurityManager -->
  27. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  28. <property name="realm" ref="userRealm"/>
  29. <!-- 给shiro添加缓存配置 -->
  30. <property name="cacheManager" ref="cacheManager"></property>
  31. </bean>
  32. <!-- 配置自定义的Realm -->
  33. <bean id="userRealm" class="cn.wolfcode.shiro.realm.UserRealm">
  34. <!-- 加密器 -->
  35. <property name="credentialsMatcher" ref="credentialsMatcher" />
  36. </bean>
  37. <!-- 在自定义的realm那个类里还要指定盐 -->
  38. <bean id="credentialsMatcher"
  39. class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
  40. <!-- 加密算法 -->
  41. <property name="hashAlgorithmName" value="md5" />
  42. <!-- 散列次数 -->
  43. <property name="hashIterations" value="3" />
  44. </bean>
  45.  
  46. <!-- 开启aop,对类代理;并开启shiro注解支持 -->
  47. <aop:config proxy-target-class="true"></aop:config>
  48. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  49. <property name="securityManager" ref="securityManager" />
  50. </bean>
  51.  
  52. <!-- 缓存管理器 -->
  53. <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
  54. <property name="cacheManager" ref="ehCacheManager"/>
  55. </bean>
  56. <bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  57. <property name="configLocation" value="classpath:shiro-ehcache.xml" />
  58. <property name="shared" value="true"></property>
  59. </bean>

4、实现自己的realm

  1. public class UserRealm extends AuthorizingRealm {
  2. @Override
  3. public String getName() {
  4. return "UserRealm";
  5. }
  6. @Override
  7. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  8. String principal = (String) token.getPrincipal();
  9. if(!"admin".equals(principal)){
  10. return null;
  11. }
  12. Employee currentUser = new Employee();
  13. currentUser.setName(principal);
  14. currentUser.setPassword("1");
  15. currentUser.setAdmin(true);
  16. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),getName());
  17. return authenticationInfo;
  18. }
  19. @Override
  20. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  21. Employee currentUser = (Employee) principals.getPrimaryPrincipal();
  22. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  23. List<String> roles = new ArrayList<String>();
  24. roles.addAll(Arrays.asList("HR MGR","ORDER MGR"));
  25. authorizationInfo.addRoles(roles);
  26. List<String> perms = new ArrayList<String>();
  27. perms.addAll(Arrays.asList("employee:view","employee:delete"));
  28. authorizationInfo.addStringPermissions(perms);
  29. return authorizationInfo;
  30. }
  31. }

5、 实现登陆方法

Suject 会自动创建,不需要我们配置;相应的登陆方法也会自动调用,不需要我们写。

  1. //此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
  2. @RequestMapping("/login")
  3. public String login(Model model, HttpServletRequest req) throws Exception{
  4. //如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
  5. String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
  6. //根据shiro返回的异常类路径判断,抛出指定异常信息
  7. if(exceptionClassName!=null){
  8. if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
  9. //最终会抛给异常处理器
  10.  
  11. model.addAttribute("errorMsg", "账号不存在");
  12. } else if (IncorrectCredentialsException.class.getName().equals(
  13. exceptionClassName)) {
  14. model.addAttribute("errorMsg", "用户名/密码错误");
  15. } else {
  16. //最终在异常处理器生成未知错误.
  17. model.addAttribute("errorMsg", "其他异常信息");
  18. }
  19. }
  20. //登陆失败还到login页面
  21. return "forward:/login.jsp";
  22. }

6、缓存管理(登陆时把当前用户的权限缓存起来,之后不需要再次查询)

  a、添加依赖

  1. <dependency>
  2. <groupId>org.apache.shiro</groupId>
  3. <artifactId>shiro-ehcache</artifactId>
  4. <version>1.2.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>net.sf.ehcache</groupId>
  8. <artifactId>ehcache-core</artifactId>
  9. <version>2.6.8</version>
  10. </dependency>

  b、securityManager引用缓存管理器(如上)

  c、配置缓存管理器,并指定缓存框架配置文件路径(如上)

    ehcache版本在2.5.0以下,需要配置如下:
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
      <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"></property>
    </bean>
    ehcache版本在2.5.0以上,需要配置如下:
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
      <property name="cacheManager" ref="ehCacheManager"/>
    </bean>
    <bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
      <property name="configLocation" value="classpath:shiro-ehcache.xml" />
      <property name="shared" value="true"></property>
    </bean>

  d、配置 shiro-ehcache.xml 文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache>
  3. <defaultCache
  4. maxElementsInMemory="1000"
  5. eternal="false"
  6. timeToIdleSeconds="120"
  7. timeToLiveSeconds="120"
  8. memoryStoreEvictionPolicy="LRU">
  9. </defaultCache>
  10. </ehcache>

7、清除缓存

  如果用户正常退出,缓存自动清空;如果用户非正常退出,缓存自动清空。

  如果修改了用户的权限,而用户不退出系统,修改的权限无法立即生效;用户退出并再次登陆系统时,shiro会自动调用realm从数据库重新获取权限数据,才会使修改的权限得以生效。

  如果在修改权限后想要立即生效,需要清除缓存,可以调用realm的clearCache方法。

  1. // 在realm中定义该方法,在角色或权限service中,delete或者update方法里来调用
  2. // 清除缓存
  3. public void clearCached() {
  4. PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
  5. super.clearCache(principals);
  6. }

spring shiro 集成的更多相关文章

  1. 十一、Spring Boot 集成Shiro和CAS

    1.Shiro 是什么?怎么用? 2.Cas 是什么?怎么用? 3.最好有spring基础 首先看一下下面这张图: 第一个流程是单纯使用Shiro的流程. 第二个流程是单纯使用Cas的流程. 第三个图 ...

  2. spring中集成shiro

    Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用Spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成. 在示 ...

  3. Spring Boot 集成Shiro和CAS

    Spring Boot 集成Shiro和CAS 标签: springshirocas 2016-01-17 23:03 35765人阅读 评论(22) 收藏 举报  分类: Spring(42)  版 ...

  4. 解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题

    如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天 ...

  5. Spring Boot集成Shiro实战

    Spring Boot集成Shiro权限验证框架,可参考: https://shiro.apache.org/spring-boot.html 引入依赖 <dependency> < ...

  6. cas+tomcat+shiro实现单点登录-4-Apache Shiro 集成Cas作为cas client端实现

    目录 1.tomcat添加https安全协议 2.下载cas server端部署到tomcat上 3.CAS服务器深入配置(连接MYSQL) 4.Apache Shiro 集成Cas作为cas cli ...

  7. Spring项目集成ShiroFilter简单配置

    Shiros是我们开发中常用的用来实现权限控制的一种工具包,它主要有认证.授权.加密.会话管理.与Web集成.缓存等功能.我是从事javaweb工作的,我就经常遇到需要实现权限控制的项目,之前我们都是 ...

  8. spring-boot-2.0.3应用篇 - shiro集成

    前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...

  9. Shiro集成web环境[Springboot]-基础使用

    Shiro集成web环境[Springboot] 1.shiro官网查找依赖的jar,其中shiro-ehcache做授权缓存时使用,另外还需要导入ehcache的jar包 <dependenc ...

随机推荐

  1. Linux CentOS7系统探索

    这两天,突发奇想,想着用着微软家的windows系统很多年了,也想尝试一下其他的操作系统.很快的就想到了Linux操作系统,它不是面向用户的,而是面向服务器的,在服务器端的市场中占了很大的市场份额,备 ...

  2. Windows10下搭建TensorFlow环境

    转载请注明源出处:http://www.cnblogs.com/lighten/p/6753695.html 这篇文章介绍了一下在Windows上安装TensorFlow的步骤,主要是翻译了一下官方的 ...

  3. linux中查找某端口,并关闭对应的端口

    1,netstat -ntlp  (n表示不反向域名杰斯 t表示查看tcp协议的连接 l查看正在监听端口 p获取进程号和端口) 2,然后直接kill -9 端口号 参考全文:https://linux ...

  4. linux安装扩展总结

    ---恢复内容开始--- 1.安装php 模块安装命令. wget http://pear.php.net/go-pear 执行 php go_pear 如果是php7 wget http://pea ...

  5. 四则运算2及psp0设计

    随机生成运算式,要求: 1.题目避免重复. 2.可定制(数量/打印方式). 3.可以控制一下参数. 要求:是否有乘除法,是否有括号,数值范围,加减有无负数,除法有无余数. 刚开始看到这样一个题目感觉还 ...

  6. Chapter 3 Phenomenon——9

    "You were over there," I suddenly remembered, and his chuckle stopped short. “你之前不在这里”我突然记 ...

  7. SSH和SSL比较

    一.SSH介绍 什么是SSH? 传统的网络服务程序,如:ftp.pop和telnet在本质上都是不安全的,因为它们在网络上用明文传送口令和数据, 别有用心的人非常容易就可以截 获这些口令和数据.而且, ...

  8. C#实现软件授权,限定MAC运行(软件license管理,简单软件注册机制)

    一个绿色免安装软件,领导临时要求加个注册机制,不能让现场工程师随意复制.事出突然,只能在现场开发(离开现场软件就不受我们控了).花了不到两个小时实现了简单的注册机制,稍作整理. 基本原理:1.软件一运 ...

  9. 远程桌面如何向远程的计算机发送ctrl+alt+del

    远程桌面如何向远程的计算机发送ctrl+alt+del ? 可以使用 ctrl+alt+end 组合键代替 ctrl+alt+del 组合键

  10. 【模板 && 拓扑】 Dijkstra 单源最短路径算法

    话不多说上代码 链式前向星233 #include<bits/stdc++.h> using namespace std; ,_max=0x3fffffff; //链式前向星 struct ...