---
title: "spring 集成shiro 之 自定义过滤器shiroFilter"
author: "coffeehot"
date: "2015-11-26T13:46:10Z"
tags: []
categories: ["企业架构"]
slug: "spring-shiro-shirofilter"
draft: false
lastmod: "2015-11-26T13:46:10Z"
id: 2259370
url: "https://coffeehot.iteye.com/blog/2259370"
---

转：[http://blog.csdn.net/shuishouhcd/article/details/9077379](http://blog.csdn.net/shuishouhcd/article/details/9077379)

 

最近一段时间，我一直在将shiro集成到我的一个项目中，用作认证和授权处理。

 

            shiro对我来说是个新东西，以下是我学习过的内容：

 

            [http://shiro.apache.org/authorization.html](http://shiro.apache.org/authorization.html)

            [http://www.cnblogs.com/skyme/archive/2011/09/11/2173760.html](http://www.cnblogs.com/skyme/archive/2011/09/11/2173760.html)  系列

            [http://www.infoq.com/cn/articles/apache-shiro](http://www.infoq.com/cn/articles/apache-shiro)

            [http://kdboy.iteye.com/blog/1103794](http://kdboy.iteye.com/blog/1103794)

[http://www.ibm.com/developerworks/cn/java/j-lo-shiro/](http://www.ibm.com/developerworks/cn/java/j-lo-shiro/)

 

如果我那个地方没说明白，可以看这些。

 集成shiro,需要配置web.xml文件，spring的applicationContext.xml配置文件（当然，独立配置一个shiro.xml文件交给spring容器处理也是可以的）。

web.xml文件中的配置：

**\[html]** [view plain](http://blog.csdn.net/wxwzy738/article/details/10992161 "view plain")[copy](http://blog.csdn.net/wxwzy738/article/details/10992161 "copy")

 

01. &lt;!-- shiro filter的名字是shiroFilter,那么在spring的配置文件中要有一个名字为shiroFilter的bean--&gt;
02. &lt;filter&gt;
03. &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt;
04. &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
05. &lt;init-param&gt;
06. &lt;param-name&gt;targetFilterLifecycle&lt;/param-name&gt;
07. &lt;param-value&gt;true&lt;/param-value&gt;
08. &lt;/init-param&gt;
09. &lt;/filter&gt;
10. &lt;filter-mapping&gt;
11. &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt;
12. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
13. &lt;/filter-mapping&gt;

applicationContext.xml文件中的配置：

 

**\[html]** [view plain](http://blog.csdn.net/wxwzy738/article/details/10992161 "view plain")[copy](http://blog.csdn.net/wxwzy738/article/details/10992161 "copy")

 

01. &lt;!-- 自定义的Shiro Filter--&gt;
02. &lt;bean id="simplePermFilter" class="frame.security.PermissionsAuthorizationFilter"&gt;&lt;/bean&gt;
03. &lt;bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"&gt;
04. &lt;property name="securityManager" ref="securityManager" /&gt;
05. &lt;property name="loginUrl" value="/login" /&gt;
06. &lt;property name="successUrl" value="/user/list" /&gt;
07. &lt;property name="unauthorizedUrl" value="/login" /&gt;
08. &lt;property name="filters"&gt;
09. &lt;map&gt;
10. &lt;entry key="sperm" value-ref="simplePermFilter"/&gt;
11. &lt;/map&gt;
12. &lt;/property&gt;
13. &lt;property name="filterChainDefinitions"&gt;
14. &lt;value&gt;
15. /Flat-UI-master/\*\*=anon
16. /index.jsp* = anon
17. /test.jsp\*=anon
18. /jsp/\** = authc
19. /test/objT.do = sperm
20. &lt;/value&gt;
21. &lt;/property&gt;
22. &lt;/bean&gt;
23. &lt;!--设置自定义realm --&gt;
24. &lt;bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"&gt;
25. &lt;property name="realm" ref="myRealm" /&gt;
26. &lt;/bean&gt;
27. &lt;!-- 配置shiro bean processor--&gt;
28. &lt;bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /&gt;
29. &lt;!--myRealm 继承自AuthorizingRealm--&gt;
30. &lt;bean id="myRealm" class="frame.security.MonitorRealm" &gt;&lt;/bean&gt;
31. &lt;bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"&gt;
32. &lt;property name="staticMethod"
33. value="org.apache.shiro.SecurityUtils.setSecurityManager" /&gt;
34. &lt;property name="arguments" ref="securityManager" /&gt;
35. &lt;/bean&gt;

 

 

代码说明：

1. shiroFilter 中 loginUrl 为登录页面地址，successUrl 为登录成功页面地址（如果首先访问受保护 URL 登录成功，则跳转到实际访问页面），unauthorizedUrl 认证未通过访问的页面（前面提到的“未经授权页面”）。
2. shiroFilter 中 filters 属性，formAuthenticationFilter 配置为基于表单认证的过滤器。
3. shiroFilter 中 filterChainDefinitions 属性，anon 表示匿名访问（不需要认证与授权），authc 表示需要认证，perms\[SECURITY\_ACCOUNT\_VIEW] 表示用户需要提供值为“SECURITY\_ACCOUNT\_VIEW”Permission 信息。由此可见，连接地址配置为 authc 或 perms\[XXX] 表示为受保护资源。
4. securityManager 中 realm 属性，配置为我们自己实现的 Realm。关于 Realm，参见前面“Shiro Realm”章节。
5. myShiroRealm 为我们自己需要实现的 Realm 类，为了减小数据库压力，添加了缓存机制。
6. shiroCacheManager 是 Shiro 对缓存框架 EhCache 的配置。

MonitorRealm.java 是自定义的realm,读取数据库的用户信息，和授权信息。

 

 PermissionsAuthorizationFilter.java 是自定义的过滤器，来实现自己需要的授权过滤方式。

**\[java]** [view plain](http://blog.csdn.net/wxwzy738/article/details/10992161 "view plain")[copy](http://blog.csdn.net/wxwzy738/article/details/10992161 "copy")

 

01. public class MonitorRealm extends AuthorizingRealm{
02. @Autowired
03. private DAO dao;&lt;span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);"&gt;//这里自己需要什么就注入什么。  &lt;/span&gt;
04. public MonitorRealm() {
05. super();
06. }
07. /\**
08. * 授权操作，决定那些角色可以使用那些资源
09. \*/
10. @Override
11. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
12. //&lt;span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);"&gt;TODO &lt;/span&gt;&lt;span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);"&gt;访问授权信息&lt;/span&gt;
13. return info;
14. }
15. /\**
16. * 认证操作，判断一个请求是否被允许进入系统
17. \*/
18. @Override
19. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
20. //&lt;span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px;"&gt;TODO 用户认证信息  &lt;/span&gt;
21. return info;
22. }
23. }

 

**\[java]** [view plain](http://blog.csdn.net/wxwzy738/article/details/10992161 "view plain")[copy](http://blog.csdn.net/wxwzy738/article/details/10992161 "copy")

 

1. public class PermissionsAuthorizationFilter extends AuthorizationFilter {
2. public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
3. &lt;span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);"&gt; //自定义过滤器逻辑&lt;/span&gt;
4. return true;
5. }
6. }

配置自定义过滤器的关键是配置文件中 的这几句

 

**\[html]** [view plain](http://blog.csdn.net/wxwzy738/article/details/10992161 "view plain")[copy](http://blog.csdn.net/wxwzy738/article/details/10992161 "copy")

 

01. &lt;property name="filters"&gt;
02. &lt;map&gt;
03. &lt;entry key="sperm" value-ref="simplePermFilter"/&gt;
04. &lt;/map&gt;
05. &lt;/property&gt;
06. &lt;property name="filterChainDefinitions"&gt;
07. &lt;value&gt;
08. ...
09. /test/objT.do ="sperm"
10. &lt;/value&gt;
11. &lt;/property&gt;

颜色相同的地方一定要一样，表示用某个过滤器过滤指定路径。因为这个我费了好长时间。

 

 

org.apache.shiro.spring.web.ShiroFilterFactoryBean   的作用是通过spring来初始化shiro的工作环境。如果一个请求进来，shiro的过滤器会先工作，过滤器会调用realm中的授权或认证的方法来获取授权或认证信息。