日期:2014-05-16  浏览次数:20607 次

如何将Apache Shiro集成到基于Spring的应用
本文主要介绍如何将Apache Shiro集成到基于Spring的应用。

Shiro兼容javabean使得它能很好的与Spring XML或其他基于Spring的配置方式集成。在基于Shiro的应用程序中的SecurityManager是单例的。不过,SecurityManager不一定是静态单例,但是不论是否是静态单例,必须保证一个应用程序中只有一个SecurityManager的实例。

独立的应用程序

下面是在Spring的应用程序中以最简单的方式配置单例SecurityManager:

<!-- 定义连接后台安全数据源的realm -->
<bean id="myRealm" class="...">
   ...
</bean>
<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
   <!-- 单realm应用。如果有多个realm,使用‘realms’属性代替 -->
   <property name="realm" ref="myRealm"/>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 最简单的集成,是将securityManager bean配置成一个静态单例,也就是让            SecurityUtils.*
下的所有方法在任何情况下都起作用。在web应用中不要将securityManager bean配置为静态单例,
具体方式请参阅下文中的‘Web Application’部分 -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
   <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
   <property name="arguments" ref="securityManager"/>
</bean>
Web应用程序

Shiro对基于Spring的Web应用提供了完美的支持,web应用中,Shiro可控制的web请求必须经过Shiro主过滤器的拦截。Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行。

Shiro1.0版本前,Spring web应用使用混合方式进行配置,在web.xml中定义Shiro的过滤器和它所有的配置,而在Spring XML中定义SecurityManager。这样有些别扭,因为第一你没办法将所有的配置放到一个位置;第二没法最大发挥Spring提供配置上的优点,比如PropertyPlaceholderConfigurer或者通过抽象beans来合并配置。

在Shiro1.0或更高版本中,所有的Shiro配置都放到Spring XML中,这样做进一步发挥了Spring配置机制的优势。

下面是如何在基于Spring的web应用中配置Shiro:

web.xml
除了定义ContextLoaderListener, Log4jConfigListener等Spring元素外,只要在web.xml中增加如下的filter和filter-mapping:

<!-- filter-name对应applicationContext.xml中定义的名字为“shiroFilter”的bean -->
<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>
...
<!-- 使用“/*”匹配所有请求,保证所有的可控请求都经过Shiro的过滤。通常这个filter-mapping
放置到最前面(其他filter-mapping前面),保证它是过滤器链中第一个起作用的 -->
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
applicationContext.xml
在applicationContext.xml中定义SecurityManager和web.xml中使用的名字叫shiroFilter的bean

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!-- 可根据项目的URL进行替换 -->
    <property name="loginUrl" value="/login.jsp"/>
    <property name="successUrl" value="/home.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    <!-- 因为每个已经定义的javax.servlet.Filter类型的bean都可以在链的定义中通过bean名
    称获取,所以filters属性不是必须出现的。但是可以根据需要通过filters属性替换filter
    实例或者为filter起别名 -->
    <property name="filters">
        <util:map>
            <entry key="anAlias" value-ref="someFilter"/>
        </util:map>
  &nb