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

在示例之前,需要导入shiro-spring及spring-context依赖,具体请参考pom.xml。

spring-beans.xml配置文件提供了基础组件如DataSource、DAO、Service组件的配置。

JavaSE应用

spring-shiro.xml提供了普通JavaSE独立应用的Spring配置:

  1. <!-- 缓存管理器 使用Ehcache实现 -->
  2. <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
  3. <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
  4. </bean>
  5. <!-- 凭证匹配器 -->
  6. <bean id="credentialsMatcher" class="
  7. com.github.zhangkaitao.shiro.chapter12.credentials.RetryLimitHashedCredentialsMatcher">
  8. <constructor-arg ref="cacheManager"/>
  9. <property name="hashAlgorithmName" value="md5"/>
  10. <property name="hashIterations" value="2"/>
  11. <property name="storedCredentialsHexEncoded" value="true"/>
  12. </bean>
  13. <!-- Realm实现 -->
  14. <bean id="userRealm" class="com.github.zhangkaitao.shiro.chapter12.realm.UserRealm">
  15. <property name="userService" ref="userService"/>
  16. <property name="credentialsMatcher" ref="credentialsMatcher"/>
  17. <property name="cachingEnabled" value="true"/>
  18. <property name="authenticationCachingEnabled" value="true"/>
  19. <property name="authenticationCacheName" value="authenticationCache"/>
  20. <property name="authorizationCachingEnabled" value="true"/>
  21. <property name="authorizationCacheName" value="authorizationCache"/>
  22. </bean>
  23. <!-- 会话ID生成器 -->
  24. <bean id="sessionIdGenerator"
  25. class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
  26. <!-- 会话DAO -->
  27. <bean id="sessionDAO"
  28. class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
  29. <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
  30. <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
  31. </bean>
  32. <!-- 会话验证调度器 -->
  33. <bean id="sessionValidationScheduler"
  34. class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
  35. <property name="sessionValidationInterval" value="1800000"/>
  36. <property name="sessionManager" ref="sessionManager"/>
  37. </bean>
  38. <!-- 会话管理器 -->
  39. <bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">
  40. <property name="globalSessionTimeout" value="1800000"/>
  41. <property name="deleteInvalidSessions" value="true"/>
  42. <property name="sessionValidationSchedulerEnabled" value="true"/>
  43. <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
  44. <property name="sessionDAO" ref="sessionDAO"/>
  45. </bean>
  46. <!-- 安全管理器 -->
  47. <bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
  48. <property name="realms">
  49. <list><ref bean="userRealm"/></list>
  50. </property>
  51. <property name="sessionManager" ref="sessionManager"/>
  52. <property name="cacheManager" ref="cacheManager"/>
  53. </bean>
  54. <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
  55. <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
  56. <property name="staticMethod"
  57. value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
  58. <property name="arguments" ref="securityManager"/>
  59. </bean>
  60. <!-- Shiro生命周期处理器-->
  61. <bean id="lifecycleBeanPostProcessor"
  62. class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

可以看出,只要把之前的ini配置翻译为此处的spring xml配置方式即可,无须多解释。LifecycleBeanPostProcessor用于在实现了Initializable接口的Shiro bean初始化时调用Initializable接口回调,在实现了Destroyable接口的Shiro bean销毁时调用 Destroyable接口回调。如UserRealm就实现了Initializable,而DefaultSecurityManager实现了Destroyable。具体可以查看它们的继承关系。

测试用例请参考com.github.zhangkaitao.shiro.chapter12.ShiroTest。

Web应用

Web应用和普通JavaSE应用的某些配置是类似的,此处只提供一些不一样的配置,详细配置可以参考spring-shiro-web.xml。

  1. <!-- 会话Cookie模板 -->
  2. <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
  3. <constructor-arg value="sid"/>
  4. <property name="httpOnly" value="true"/>
  5. <property name="maxAge" value="180000"/>
  6. </bean>
  7. <!-- 会话管理器 -->
  8. <bean id="sessionManager"
  9. class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
  10. <property name="globalSessionTimeout" value="1800000"/>
  11. <property name="deleteInvalidSessions" value="true"/>
  12. <property name="sessionValidationSchedulerEnabled" value="true"/>
  13. <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
  14. <property name="sessionDAO" ref="sessionDAO"/>
  15. <property name="sessionIdCookieEnabled" value="true"/>
  16. <property name="sessionIdCookie" ref="sessionIdCookie"/>
  17. </bean>
  18. <!-- 安全管理器 -->
  19. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  20. <property name="realm" ref="userRealm"/>
  21. <property name="sessionManager" ref="sessionManager"/>
  22. <property name="cacheManager" ref="cacheManager"/>
  23. </bean>

1、sessionIdCookie是用于生产Session ID Cookie的模板;

2、会话管理器使用用于web环境的DefaultWebSessionManager;

3、安全管理器使用用于web环境的DefaultWebSecurityManager。

  1. <!-- 基于Form表单的身份验证过滤器 -->
  2. <bean id="formAuthenticationFilter"
  3. class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
  4. <property name="usernameParam" value="username"/>
  5. <property name="passwordParam" value="password"/>
  6. <property name="loginUrl" value="/login.jsp"/>
  7. </bean>
  8. <!-- Shiro的Web过滤器 -->
  9. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  10. <property name="securityManager" ref="securityManager"/>
  11. <property name="loginUrl" value="/login.jsp"/>
  12. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
  13. <property name="filters">
  14. <util:map>
  15. <entry key="authc" value-ref="formAuthenticationFilter"/>
  16. </util:map>
  17. </property>
  18. <property name="filterChainDefinitions">
  19. <value>
  20. /index.jsp = anon
  21. /unauthorized.jsp = anon
  22. /login.jsp = authc
  23. /logout = logout
  24. /** = user
  25. </value>
  26. </property>
  27. </bean>

1、formAuthenticationFilter为基于Form表单的身份验证过滤器;此处可以再添加自己的Filter bean定义;

2、shiroFilter:此处使用ShiroFilterFactoryBean来创建ShiroFilter过滤器;filters属性用于定义自己的过滤器,即ini配置中的[filters]部分;filterChainDefinitions用于声明url和filter的关系,即ini配置中的[urls]部分。

接着需要在web.xml中进行如下配置:

  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>
  4. classpath:spring-beans.xml,
  5. classpath:spring-shiro-web.xml
  6. </param-value>
  7. </context-param>
  8. <listener>
  9. <listener-class>
  10. org.springframework.web.context.ContextLoaderListener
  11. </listener-class>
  12. </listener>

通过ContextLoaderListener加载contextConfigLocation指定的Spring配置文件。

  1. <filter>
  2. <filter-name>shiroFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. <init-param>
  5. <param-name>targetFilterLifecycle</param-name>
  6. <param-value>true</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>shiroFilter</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>

DelegatingFilterProxy会自动到Spring容器中查找名字为shiroFilter的bean并把filter请求交给它处理。

其他配置请参考源代码。

Shiro权限注解

Shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用AOP的功能来进行判断,如Spring AOP;Shiro提供了Spring AOP集成用于权限注解的解析和验证。

为了测试,此处使用了Spring MVC来测试Shiro注解,当然Shiro注解不仅仅可以在web环境使用,在独立的JavaSE中也是可以用的,此处只是以web为例了。

在spring-mvc.xml配置文件添加Shiro Spring AOP权限注解的支持:

  1. <aop:config proxy-target-class="true"></aop:config>
  2. <bean class="
  3. org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  4. <property name="securityManager" ref="securityManager"/>
  5. </bean>

如上配置用于开启Shiro Spring AOP权限注解的支持;<aop:config proxy-target-class="true">表示代理类。

接着就可以在相应的控制器(AnnotationController)中使用如下方式进行注解:

  1. @RequiresRoles("admin")
  2. @RequestMapping("/hello2")
  3. public String hello2() {
  4. return "success";
  5. }

访问hello2方法的前提是当前用户有admin角色。

当验证失败,其会抛出UnauthorizedException异常,此时可以使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:

  1. @ExceptionHandler({UnauthorizedException.class})
  2. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  3. public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
  4. ModelAndView mv = new ModelAndView();
  5. mv.addObject("exception", e);
  6. mv.setViewName("unauthorized");
  7. return mv;
  8. }

如果集成Struts2,需要注意《Shiro+Struts2+Spring3 加上@RequiresPermissions 后@Autowired失效》问题:

http://jinnianshilongnian.iteye.com/blog/1850425

权限注解

  1. @RequiresAuthentication

表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。

  1. @RequiresUser

表示当前Subject已经身份验证或者通过记住我登录的。

  1. @RequiresGuest

表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。

  1. @RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)

表示当前Subject需要角色admin和user。

  1. @RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR)

表示当前Subject需要权限user:a或user:b。

示例源代码:https://github.com/zhangkaitao/shiro-example

spring中集成shiro的更多相关文章

  1. spring中集成shiro进行安全管理

    shiro是一款轻量级的安全框架,提供认证.授权.加密和会话管理四个基础功能,除此之外也提供了很好的系统集成方案. 下面将它集成到之前的demo中,在之前spring中使用aop配置事务这篇所附代码的 ...

  2. 细说shiro之五:在spring框架中集成shiro

    官网:https://shiro.apache.org/ 1. 下载在Maven项目中的依赖配置如下: <!-- shiro配置 --> <dependency> <gr ...

  3. [原]CAS和Shiro在spring中集成

    shiro是权限管理框架,现在已经会利用它如何控制权限.为了能够为多个系统提供统一认证入口,又研究了单点登录框架cas.因为二者都会涉及到对session的管理,所以需要进行集成. Shiro在1.2 ...

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

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

  5. Spring Boot 集成Shiro和CAS

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

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

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

  7. Spring Boot集成Shiro实战

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

  8. 在前后端分离的SpringBoot项目中集成Shiro权限框架

    参考[1].在前后端分离的SpringBoot项目中集成Shiro权限框架 参考[2]. Springboot + Vue + shiro 实现前后端分离.权限控制   以及跨域的问题也有涉及

  9. Spring Boot 中集成 Shiro

    https://blog.csdn.net/taojin12/article/details/88343990

随机推荐

  1. Asp.Net 之 DropDownList的使用

    这里不细说,直接上案例 <td style="width: 30px;" align="right"> 年月: </td> <td ...

  2. orcl 之 导入和导出

     dmp文件导入 //1 oracle的数据模式是:用户建在表空间上,表建在用户上 //2 一个用户的表就象自己的私有财产一样,没有自己或管理员授权别的用户是不能查询或修改的: //3 对于不同用户下 ...

  3. BZOJ4018: 小Q的幻想之乡

    Description 背景 有一天,小Q梦见自己来到了理想国的幻想之乡. 描述 有一天,小Q梦见自己来到了理想国的幻想之乡.幻想乡有无穷户居民,第i个家庭住在编号为i的房屋里,编号从1开始,到正无穷 ...

  4. Visual Studio 安装easyX且导入graphics库后,outtextxy提示未定义标示符

    1.点击 “项目” ,然后点击 “属性”. 2. 然后点击左侧 “配置与属性” 下的 “常规” ,在点击 “字符集” ,选择 “使用多字节字符集” 即可解决问题

  5. 安装 Linux 内核 4.0

    大家好,今天我们学习一下如何从Elrepo或者源代码来安装最新的Linux内核4.0.代号为‘Hurr durr I'm a sheep’的Linux内核4.0是目前为止最新的主干内核.它是稳定版3. ...

  6. R工具包一网打尽

    这里有很多非常不错的R包和工具. 该想法来自于awesome-machine-learning. 这里是包的导航清单,看起来更方便 >>>导航清单 通过这些翻译了解这些工具包,以后干 ...

  7. _itemmod_refresh

    -- 随机FM刷新设置-- 小技巧:很多服所说的装备鉴定效果可以通过这个实现,也可以对物品重新生成新的附魔--详细解说一下鉴定系统如何实现--1首先在_itemmod_enchant_groups中添 ...

  8. Bootstrap & Font Awesome 学习笔记

    学习网站:http://bootstrap.ninghao.net/index.html https://www.freecodecamp.cn http://www.runoob.com/boots ...

  9. tips 移入悬浮功能

    前景: 页面部分区域需要移入悬浮效果,当然默认的 title 也是可以的,最多只是格格不入,但是却是最为靠谱的.. 思路: 基于 jq 实例扩展 .使用立即执行函数保持功能独立. 自定义类实现功能封装 ...

  10. centos7在upgrade的时候显示:Delta RPMs disabled because /usr/bin/applydeltarpm not installed

    前面安装信息,太多,省略 总计:113 MIs this ok [y/d/N]: yDownloading packages:Delta RPMs disabled because /usr/bin/ ...