`
jinnianshilongnian
  • 浏览: 21434038 次
  • 性别: Icon_minigender_1
博客专栏
5c8dac6a-21dc-3466-8abb-057664ab39c7
跟我学spring3
浏览量:2404982
D659df3e-4ad7-3b12-8b9a-1e94abd75ac3
Spring杂谈
浏览量:2997639
43989fe4-8b6b-3109-aaec-379d27dd4090
跟开涛学SpringMVC...
浏览量:5631433
1df97887-a9e1-3328-b6da-091f51f886a1
Servlet3.1规范翻...
浏览量:257561
4f347843-a078-36c1-977f-797c7fc123fc
springmvc杂谈
浏览量:1593147
22722232-95c1-34f2-b8e1-d059493d3d98
hibernate杂谈
浏览量:248965
45b32b6f-7468-3077-be40-00a5853c9a48
跟我学Shiro
浏览量:5847500
Group-logo
跟我学Nginx+Lua开...
浏览量:698136
5041f67a-12b2-30ba-814d-b55f466529d5
亿级流量网站架构核心技术
浏览量:780438
社区版块
存档分类
最新评论

第十二章 与Spring集成——《跟我学Shiro》

阅读更多

 

目录贴: 跟我学Shiro目录贴

 

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

<!-- 缓存管理器 使用Ehcache实现 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>

<!-- 凭证匹配器 -->
<bean id="credentialsMatcher" class="
com.github.zhangkaitao.shiro.chapter12.credentials.RetryLimitHashedCredentialsMatcher">
    <constructor-arg ref="cacheManager"/>
    <property name="hashAlgorithmName" value="md5"/>
    <property name="hashIterations" value="2"/>
    <property name="storedCredentialsHexEncoded" value="true"/>
</bean>

<!-- Realm实现 -->
<bean id="userRealm" class="com.github.zhangkaitao.shiro.chapter12.realm.UserRealm">
    <property name="userService" ref="userService"/>
    <property name="credentialsMatcher" ref="credentialsMatcher"/>
    <property name="cachingEnabled" value="true"/>
    <property name="authenticationCachingEnabled" value="true"/>
    <property name="authenticationCacheName" value="authenticationCache"/>
    <property name="authorizationCachingEnabled" value="true"/>
    <property name="authorizationCacheName" value="authorizationCache"/>
</bean>
<!-- 会话ID生成器 -->
<bean id="sessionIdGenerator" 
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
<!-- 会话DAO -->
<bean id="sessionDAO" 
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
    <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
    <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
</bean>
<!-- 会话验证调度器 -->
<bean id="sessionValidationScheduler" 
class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
    <property name="sessionValidationInterval" value="1800000"/>
    <property name="sessionManager" ref="sessionManager"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">
    <property name="globalSessionTimeout" value="1800000"/>
    <property name="deleteInvalidSessions" value="true"/>
    <property name="sessionValidationSchedulerEnabled" value="true"/>
   <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
    <property name="sessionDAO" ref="sessionDAO"/>
</bean>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
    <property name="realms">
        <list><ref bean="userRealm"/></list>
    </property>
    <property name="sessionManager" ref="sessionManager"/>
    <property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" 
value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
    <property name="arguments" ref="securityManager"/>
</bean>
<!-- Shiro生命周期处理器-->
<bean id="lifecycleBeanPostProcessor" 
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。 

<!-- 会话Cookie模板 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    <constructor-arg value="sid"/>
    <property name="httpOnly" value="true"/>
    <property name="maxAge" value="180000"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" 
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="globalSessionTimeout" value="1800000"/>
    <property name="deleteInvalidSessions" value="true"/>
    <property name="sessionValidationSchedulerEnabled" value="true"/>
    <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
    <property name="sessionDAO" ref="sessionDAO"/>
    <property name="sessionIdCookieEnabled" value="true"/>
    <property name="sessionIdCookie" ref="sessionIdCookie"/>
</bean>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
    <property name="sessionManager" ref="sessionManager"/>
    <property name="cacheManager" ref="cacheManager"/>
</bean> 

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

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

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

 

<!-- 基于Form表单的身份验证过滤器 -->
<bean id="formAuthenticationFilter" 
class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
    <property name="usernameParam" value="username"/>
    <property name="passwordParam" value="password"/>
    <property name="loginUrl" value="/login.jsp"/>
</bean>
<!-- Shiro的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/login.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    <property name="filters">
        <util:map>
            <entry key="authc" value-ref="formAuthenticationFilter"/>
        </util:map>
    </property>
    <property name="filterChainDefinitions">
        <value>
            /index.jsp = anon
            /unauthorized.jsp = anon
            /login.jsp = authc
            /logout = logout
            /** = user
        </value>
    </property>
</bean> 

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

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

 

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

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:spring-beans.xml,
        classpath:spring-shiro-web.xml
    </param-value>
</context-param>
<listener>
   <listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> 

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

  

<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</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权限注解的支持: 

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

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

 

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

@RequiresRoles("admin")
@RequestMapping("/hello2")
public String hello2() {
    return "success";
} 

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

 

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

@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("exception", e);
    mv.setViewName("unauthorized");
    return mv;
} 

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

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

 

权限注解      

@RequiresAuthentication

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

 

@RequiresUser

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

 

@RequiresGuest

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

 

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

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

 

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

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

 

 

示例源代码:https://github.com/zhangkaitao/shiro-example;可加群 231889722 探讨Spring/Shiro技术。

 

 

38
6
分享到:
评论
30 楼 muzili90 2018-04-27  
抛出异常@ExceptionHandler({UnauthorizedException.class})
时总是跳转到/login 没有执行方法内容
应该是这个异常被shiro捕获默认跳转到/login
如何让自己的异常捕获 @ExceptionHandler({UnauthorizedException.class})  生效呢
29 楼 ioandy 2017-10-11  
u010018421 写道
12806474 写道
Alex丿 写道
请教一下, shiro与spring集成, 自定义了一个UserRealm, 跟踪代码发现始终没有调里面的doGetAuthorizationInfo和doGetAuthenticationInfo 。登录情况是登录不进去,一直跳到login.jsp界面, 用的是formAuthenticationFilter

没有login @Controller 对应吧,我的也是这样

我也遇到这种问题了,请问怎么解决

formAuthenticationFilter 设置的loginUrl 要跟请求的url一致。跟源码
28 楼 u010018421 2017-08-22  
12806474 写道
Alex丿 写道
请教一下, shiro与spring集成, 自定义了一个UserRealm, 跟踪代码发现始终没有调里面的doGetAuthorizationInfo和doGetAuthenticationInfo 。登录情况是登录不进去,一直跳到login.jsp界面, 用的是formAuthenticationFilter

没有login @Controller 对应吧,我的也是这样

我也遇到这种问题了,请问怎么解决
27 楼 CoderDream 2017-07-19  
sqzx10101 写道
12806474 写道
12806474 写道
Alex丿 写道
请教一下, shiro与spring集成, 自定义了一个UserRealm, 跟踪代码发现始终没有调里面的doGetAuthorizationInfo和doGetAuthenticationInfo 。登录情况是登录不进去,一直跳到login.jsp界面, 用的是formAuthenticationFilter

没有login @Controller 对应吧,我的也是这样

注意:::::::测试用户中 zhang 的密码是 1231 而不是123

求问,哪里把密码改成了1231的。。。。。


ShiroTest.test()
userService.changePassword(u1.getId(), password + "1");
26 楼 sqzx10101 2017-02-21  
12806474 写道
12806474 写道
Alex丿 写道
请教一下, shiro与spring集成, 自定义了一个UserRealm, 跟踪代码发现始终没有调里面的doGetAuthorizationInfo和doGetAuthenticationInfo 。登录情况是登录不进去,一直跳到login.jsp界面, 用的是formAuthenticationFilter

没有login @Controller 对应吧,我的也是这样

注意:::::::测试用户中 zhang 的密码是 1231 而不是123

求问,哪里把密码改成了1231的。。。。。
25 楼 wheretofindyou2 2016-12-24  
u013768040 写道
liujian123 写道
涛ge,遇到个大麻烦,我在配置Shiro的sessionValidationScheduler后系统会报错
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Validating all active sessions...
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Finished session validation.  No sessions were stopped.
这之后Spring配置的定时任务就会失效,怎样避免这个问题


你好,我也遇到了这个问题,请问你解决了吗?我比较急,如果看见了可否加qq 交流一下 158850013



这个bug貌似只有第一次登陆的时候才会出现而且我也google了好多,说是问题不大。当加上remmberMe是这个bug是不会出现的(我这里是)。
24 楼 u013768040 2016-12-19  
liujian123 写道
涛ge,遇到个大麻烦,我在配置Shiro的sessionValidationScheduler后系统会报错
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Validating all active sessions...
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Finished session validation.  No sessions were stopped.
这之后Spring配置的定时任务就会失效,怎样避免这个问题


你好,我也遇到了这个问题,请问你解决了吗?我比较急,如果看见了可否加qq 交流一下 158850013
23 楼 a001236987 2016-11-19  
涛神,我在使用你第12章的集成spring的时候,遇到了一个there is no session with id问题。我找了好几天都没找到答案,不过我实验了一下,
有以下结果:

1、当我用chapter-12的代码登录完了以后,关闭浏览器,重启服务器,再打开浏览器,session还在,无需登录就可以进入页面。

2、将chapter-12的代码和配置文件复制到一个我自己的只有相应的jar包的web项目(配置代码完全相同,只是jar包略有不同),使用上面相同的方法进行测试,会出现there is no session with id的问题。

我的看法是session持久化的问题,但这个星期一直在找这个问题找不到答案,很苦恼,想问问您有没有遇到这个问题,遇到了你是怎么解决的?或者配置的时候有哪些是需要注意的。再此先谢谢涛神的这部教程,很详细。
22 楼 haorengoodman 2016-07-14  
liujian123 写道
涛ge,遇到个大麻烦,我在配置Shiro的sessionValidationScheduler后系统会报错
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Validating all active sessions...
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Finished session validation.  No sessions were stopped.
这之后Spring配置的定时任务就会失效,怎样避免这个问题

单看这个只能猜问题,这个问题肯定还有别的更有效的信息(例如:其他的异常)
21 楼 liujian123 2016-07-12  
涛ge,遇到个大麻烦,我在配置Shiro的sessionValidationScheduler后系统会报错
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Validating all active sessions...
2016-07-12 10:51:26  [ DefaultQuartzScheduler_Worker-3:379836 ] - [ INFO ]  Finished session validation.  No sessions were stopped.
这之后Spring配置的定时任务就会失效,怎样避免这个问题
20 楼 pyzheng 2016-06-16  
supercwg 写道
涛ge,请教个还是困扰很久的问题,就是@RequiresRoles("admin")这样硬编码权限控制基本上没有实战性意义吧,毕竟权限都是经常发生变化,如果能够跟后台数据库的权限数据对应起来那才是真正有实战意义的安全呢,不知道怎么解决好呢?


这种方式有它自己的意义   比如一些应用  明显知道了哪些固定的角色  不会对角色动态增加的  就适合用这种
19 楼 dsjt 2016-05-06  
AuthorizationAttributeSourceAdvisor 能够代理 Contrller 是在哪配置的?
如何改成代理Service
18 楼 newboy2004 2015-12-14  
pyzheng 写道
pyzheng 写道
我碰到一个很奇怪的问题. 猜不到问题的原因. 无法解决.
首先我filterChainDefinitions配置是:/admin/**.do** = authc
然后我执行/admin/index.do  因为没有登录, 所以跳出去login
但是我执行/admin/menu/index.do, 反而可以进入/admin/menu/index.do里面.
不是两个星号是任意匹配么?
谢谢.


问题解决了, 好像*号无法匹配/  改成/admin/**/**.do**就可以了.



对*无法匹配/,改成/**/**才可以匹配/
17 楼 pyzheng 2015-12-01  
pyzheng 写道
我碰到一个很奇怪的问题. 猜不到问题的原因. 无法解决.
首先我filterChainDefinitions配置是:/admin/**.do** = authc
然后我执行/admin/index.do  因为没有登录, 所以跳出去login
但是我执行/admin/menu/index.do, 反而可以进入/admin/menu/index.do里面.
不是两个星号是任意匹配么?
谢谢.


问题解决了, 好像*号无法匹配/  改成/admin/**/**.do**就可以了.
16 楼 pyzheng 2015-12-01  
我碰到一个很奇怪的问题. 猜不到问题的原因. 无法解决.
首先我filterChainDefinitions配置是:/admin/**.do** = authc
然后我执行/admin/index.do  因为没有登录, 所以跳出去login
但是我执行/admin/menu/index.do, 反而可以进入/admin/menu/index.do里面.
不是两个星号是任意匹配么?
谢谢.
15 楼 mwxx 2015-10-27  
例子中MyRealm2一直是验证通过的情况,所以能正常执行到RetryLimitHashedCredentialsMatcher
如果自己写了Realm,验证密码错误或者帐号不存在的时候抛出异常,就不会进入RetryLimitHashedCredentialsMatcher 中的方法了。
14 楼 wangaowell 2015-10-14  
13 楼 bobohenda 2015-10-06  
zyg345646335 写道
总结的很好,推荐一个框架整合:
http://43.249.81.29:8080/index.html
12 楼 xiaobadi 2015-07-20  
龙哥换头像了啊,好帅
11 楼 m33707 2015-05-11  
请教下,我碰到个问题,未登陆时,shiro跳转到loginUrl,但如果是手机APP访问呢?怎么控制让他返回json。
我看到shiro是redirect,不是forward,传参数的话loginUrl对应的controller就拿不到了

相关推荐

Global site tag (gtag.js) - Google Analytics