基于web应用的Shiro入口介绍

Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。

Shiro的入口其实是一个Filter,这个Filter在spring中配置并受到spring容器的管理,既然受spring管理,那它就可以引用spring中的其他bean对象了。Shiro Filter通过DelegatingFilterProxy类对其进行代理。

以下是关于DelegatingFilterProxy的详细介绍:

    使用DelegatingFilterProxy可以将其所代理的filter作为spring容器的bean,使filter受到spring的管理,这样filter就可以引用spring里定义的其他bean了。

    DelegatingFilterProxy作为标准的Servlet2.3 Filter的代理,但是Filter的实际工作是通过将任务委派给spring管理的而且实现了Filter接口的bean来完成的。

    web.xml通常会包括DelegatingFilterProxy的定义,其中的filter-name项会对应spring容器中的一个bean的名字(也可以使用targetBeanName属性进行指定)。所有的调用请求都会首先发送到这个filter代理中去,然后再委派到spring容器中的这个bean,当然,这个bean必须要实现标准的Servlet 2.3 Filter 接口。

Shiro在web.xml和spring中的配置如下:

在web.xml中的配置:

<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>

在spring中的配置:

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
	<property name="securityManager" ref="securityManager" />
	<property name="loginUrl" value="/login.action" />
	<property name="successUrl" value="/index.jsp" />
	<property name="filters">
		<map>
			 <entry key="authc" value-ref="formAuthenticationFilter"/>
			 <entry key="resourceAuth" value-ref="resourceAuthenticationFilter"/>
		</map>
	</property>
	<property name="filterChainDefinitions">
		<value>
			/login.action = authc
			/logout.action = logout
			/common/** = anon
			/** = user,resourceAuth
		</value>
	</property>
</bean>

    Servlet Filter 接口中定义的生命周期函数(init和destroy等)默认不会被target bean自己执行,而是由spring容器执行来管理这个bean的生命周期。如果将名为"targetFilterLifecycle"的filter init-param参数设定为"true",则target bean的Filter.init和Filter.destroy的生命周期函数的调用就可以由servlet container来执行了。

猜你喜欢

转载自chenjumin.iteye.com/blog/2280930
今日推荐