Apache Shiro 框架与 Web 集成

前言

在《Apache Shiro 框架》中提到,Apache Shiro是 Java 的一个强大易用的安全(权限)框架,提供了认证、授权、加密、会话管理、与 Web 集成、缓存等功能,本文主要记录本人在学习使用 Apache Shiro 框架与 Web 集成过程中一些总结及感悟,学习过程中通过新建项目边学边练来加深理解。


与 Web 的集成

Shiro 提供了与 Web 集成的支持,其通过一个 ShiroFilter 入口来拦截需要安全控制的 URL,然后进行相应的控制。ShiroFilter 类似于如 Strut2/SpringMVC 这种 web 框架的前端控制器,是安全控制的入口点,其负责读取配置(如 ini 配置文件),然后判断 URL 是否需要登录 / 权限等工作。《Apache Shiro 框架默认过滤器及 URL 匹配》对于 Shiro 框架默认过滤器及 URL 匹配做了详细的讲解。

Shiro 与 Web 的集成的配置详解

1. 配置 Spring 及 SpringMVC

Spring 及 SpringMVC 配置此处略,详见《Apache SpringMvc 配置详解及源码分析》。

2. 配置 Shiro 的 SecurityManager

securityManager 安全管理器,它相当于 SpringMVC 中的 DispatcherServlet;是 Shiro 的心脏所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证、授权、会话及缓存的管理,其配置如下:

1
2
3
4
5
6
7
8
9
10
11
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>

3. 配置 CacheManager 及 authenticator

CacheManager 缓存控制器,用来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能;Authenticator 负责 Subject 认证,是一个扩展点,可以自定义实现;可以使用认证策略(Authentication Strategy),即什么情况下算用户认证通过了。

1
2
3
4
5
6
7
8
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>

4. 配置 Realm

Shiro 从 Realm 获取安全数据(如用户、角色、权限),可以有一个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是内存实现等等;由用户提供;所以一般在应用中都需要实现自己的 Realm。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean -->
<bean id="jdbcRealm" class="com.syshlang.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.syshlang.shiro.realms.SecondRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>

5. 配置 LifecycleBeanPostProcessor

LifecycleBeanPostProcessor 将 Initializable 和 Destroyable 的实现类统一在其内部自动分别调用了 Initializable.init () 和 Destroyable.destroy () 方法,从而达到管理 shiro bean 生命周期的目的, 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法。

1
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

6. 启用 IOC 容器中使用 shiro 的注解

启用 IOC 容器中使用 shiro 的注解,但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用。

1
2
3
4
5
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>

7. 配置 Shiro 的 shiroFilter

Shiro 的 DefaultFilter 在整个 Shiro 架构中的作用便是用来拦截所有请求。在 Shiro DefaultFilter 中我们配置了 filterChainDefinitions 属性。filterChainDefinitions 的作用便是对所有被 Shiro 拦截的请求做声明,下面是一个标准的 DefaultFilter 和 filterChainDefinitions 的配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/list.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
<!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
1). anon 可以被匿名访问
2). authc 必须认证(即登录)后才可能访问的页面.
3). logout 登出.
4). roles 角色过滤器
-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout

/user.jsp = roles[user]
/admin.jsp = roles[admin]

# everything else requires authentication:
/** = authc
</value>
</property>
</bean>

从以上的配置我们可以预见一个问题,那就是倘若 filterChainDefinitions 的声明过多的话会导致该配置文件冗余臃肿。在 Shiro 的源代码中 filterChainDefinition 本身是一个 linkedHashMap,所以我们可以通过工厂设计模式来创建一个 filterChainDefinitionMap。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/list.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
</bean>

<!-- 配置一个 bean, 该 bean 实际上是一个 Map. 通过实例工厂方法的方式 -->
<bean id="filterChainDefinitionMap"
factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefinitionMap"></bean>

<bean id="filterChainDefinitionMapBuilder"
class="com.syshlang.shiro.factory.FilterChainDefinitionMapBuilder"></bean>
FilterChainDefinitionMapBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author sunys
*/
public class FilterChainDefinitionMapBuilder {
public LinkedHashMap<String, String> buildFilterChainDefinitionMap() {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("/login.jsp", "anon");
map.put("/shiro/login", "anon");
map.put("/shiro/logout", "logout");
map.put("/user.jsp", "authc,roles[user]");
map.put("/admin.jsp", "authc,roles[admin]");
map.put("/list.jsp", "user");
map.put("/**", "authc");
return map;
}
}

在 web.xml 文件中配置 Shiro 的 shiroFilter 过滤器。

web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
<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 实际上是 Filter 的一个代理对象,DelegatingFilterProxy 作用是自动到 Spring IOC 容器中查找名字为 shiroFilter(filter-name)的 bean 并把所有 Filter 的操作委托给它,也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id。
因为 Shiro 会来 IOC 容器中查找和名字对应的 filter bean,所以配置 Shiro 的 filter bean 的 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的一致,若不一致,则会抛出: NoSuchBeanDefinitionException。
shiro 框架在 Java Web 应用中使用时,本质上是通过 filter 方式集成的。也就是说,它是遵循过滤器链规则的:filter 的执行顺序与在 web.xml 中定义的顺序一致

以上所涉及到的配置项在《Apache Shiro 框架》中都有详细的讲解。

附:配置清单

applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>

<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<bean id="jdbcRealm" class="com.syshlang.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>

<bean id="secondRealm" class="com.syshlang.shiro.realms.SecondRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/list.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>

<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>

<!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
1). anon 可以被匿名访问
2). authc 必须认证(即登录)后才可能访问的页面.
3). logout 登出.
4). roles 角色过滤器
-->
<!--
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout

/user.jsp = roles[user]
/admin.jsp = roles[admin]

# everything else requires authentication:
/** = authc
</value>
</property>
-->
</bean>

<!-- 配置一个 bean, 该 bean 实际上是一个 Map. 通过实例工厂方法的方式 -->
<bean id="filterChainDefinitionMap"
factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefinitionMap"></bean>

<bean id="filterChainDefinitionMapBuilder"
class="com.syshlang.shiro.factory.FilterChainDefinitionMapBuilder"></bean>

<bean id="shiroService"
class="com.syshlang.shiro.services.ShiroService"></bean>
</beans>