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配置:

Java代码  
  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。

Java代码  
  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。

Java代码  
  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中进行如下配置:

Java代码  
  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配置文件。

Java代码  
  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权限注解的支持:

Java代码  
  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)中使用如下方式进行注解:

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

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

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

Java代码  
  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

权限注解

Java代码  
  1. @RequiresAuthentication

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

Java代码  
  1. @RequiresUser

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

Java代码  
  1. @RequiresGuest

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

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

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

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

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

Shiro学习(12)与Spring集成的更多相关文章

  1. Activiti学习——Activiti与Spring集成

    转: Activiti学习——Activiti与Spring集成 与Spring集成 基础准备 目录结构 相关jar包 Activiti的相关jar包 Activiti依赖的相关jar包 Spring ...

  2. Shiro学习(22)集成验证码

    在做用户登录功能时,非常多时候都须要验证码支持,验证码的目的是为了防止机器人模拟真有用户登录而恶意訪问,如暴力破解用户password/恶意评论等. 眼下也有一些验证码比較简单,通过一些OCR工具就能 ...

  3. Spring第12篇—— Spring对Hibernate的SessionFactory的集成功能

    由于Spring和Hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心 ...

  4. Shiro学习笔记(5)——web集成

    Web集成 shiro配置文件shiroini 界面 webxml最关键 Servlet 測试 基于 Basic 的拦截器身份验证 Web集成 大多数情况.web项目都会集成spring.shiro在 ...

  5. Shiro之身份认证、与spring集成(入门级)

    目录 1. Shro的概念 2. Shiro的简单身份认证实现 3. Shiro与spring对身份认证的实现 前言: Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境 ...

  6. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(二)shiro权限注解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(二)shiro权限注解 shiro注 ...

  7. 2017.2.13 开涛shiro教程-第十二章-与Spring集成(一)配置文件详解

    原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. 第十二章-与Spring集成(一)配置文件详解 1.pom.xml ...

  8. Activiti工作流学习(三)Activiti工作流与spring集成

    一.前言 前面Activiti工作流的学习,说明了Activiti的基本应用,在我们开发中可以根据实际的业务参考Activiti的API去更好的理解以及巩固.我们实际的开发中我们基本上都使用sprin ...

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

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

  10. Spring集成shiro做登陆认证

    一.背景 其实很早的时候,就在项目中有使用到shiro做登陆认证,直到今天才又想起来这茬,自己抽空搭了一个spring+springmvc+mybatis和shiro进行集成的种子项目,当然里面还有很 ...

随机推荐

  1. springDataRedis 依赖

    <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit ...

  2. AI加持的阿里云飞天大数据平台技术揭秘

    摘要:2019云栖大会大数据&AI专场,阿里云智能计算平台事业部研究员关涛.资深专家徐晟来为我们分享<AI加持的阿里云飞天大数据平台技术揭秘>.本文主要讲了三大部分,一是原创技术优 ...

  3. 「NOI2017」游戏 解题报告

    「NOI2017」游戏 \(d\)这么小,你考虑直接对\(d\)个东西暴力 枚举\(x\)为\(a\)或\(b\)(\(c\)就不用了,因为\(a,b\)已经包含\(c\))了,剩下的就是个\(2-s ...

  4. Network基础(四):MAC地址表及邻居信息查看、配置接口速率及双工模式、配置交换机管理IP

    一.MAC地址表及邻居信息查看 目标: 本例要求为修改计算机名并加入工作组: 查看交换机MAC地址表 查看CISCO设备邻居信息 方案: 网络拓扑,如下图所示. 步骤: 步骤一:查看交换机sw1的ma ...

  5. shell从字符串中提取子串(正则表达式)

    通过试验,可以通过grep.sed两种方式实现. 假设需要提取libgcc-4.8.5-4.h5.x86_64.rpm中的版本号. grep echo "libgcc-4.8.5-4.h5. ...

  6. 【计算机网络mooc】二、物理层

    1.物理层基本概念 物理层只考虑传输bit流,不包括网线等传输媒体(可认为是第0层),屏蔽传输媒体的差异,不同的传输媒体定义不同标准. 主要任务:确定与传输媒体的接口的特性. 机械特性:网线上面的水晶 ...

  7. 购买 Linux VPS 服务器后简单的安全设置

    我们在购买了 Linux 系统的 VPS 或服务器后,一般的商家都会给你一个 root 权限的账号,并且默认的密码不会太长,这是很不安全的.经常有客户因为弱口令而被黑客暴力破解密码导致 VPS 服务器 ...

  8. 图片模式CMYK和RGB在浏览器下的变化

    手机浏览器里面不能显示出模式为CMYK的图片, 模式为CMYK的图片在IE浏览器里面显示和模式为RGB的一样 模式为CMYK的图片在火狐里面显示有色差

  9. CMDB 调研报告

    基础概念 1.什么是CMDB CMDB——配置管理数据库,通过识别.控制.维护,检查企业的IT资源,从而高效控制与管理不断变化的IT基础架构与IT服务,并为其它流程,例如事故管理.问题管理.变更管理. ...

  10. python作业/练习/实战:生成随机密码

    作业要求1.写一个函数,函数的功能是生成一批密码,存到文件里面 def gen_password(num): #num代表生成多少条密码2.密码复杂度要求 1)长度在,8-16位之间 2)密码必须包括 ...