3 配置applicationContext-security.xml
3.1 FilterChainProxy过滤器链
FilterChainProxy会按顺序来调用一组filter,使这些filter即能完成验证授权的本质工作,又能享用Spring Ioc的功能来方便的得到其它依赖的资源。FilterChainProxy配置如下:
class ="org.springframework.security.util.FilterChainProxy" >
2 < property name ="filterInvocationDefinitionSource" >
3 < value > <![CDATA[
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
4 PATTERN_TYPE_APACHE_ANT
/**=httpSessionContextIntegrationFilter,logoutFilter,
5 authenticationProcessingFilter,securityContextHolderAwareRequestFilter,
6 rememberMeProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,
7 filterSecurityInterceptor
8 ]]> </ value >
9 </ property >
10 </ bean >
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON 定义URL在匹配之前必须先转为小写,PATTERN_TYPE_APACHE_ANT 定义了使用Apache ant的匹配模式,/**定义的将等号后面的过滤器应用在那些URL上,这里使用全部URL过滤,每个过滤器之间都适用逗号分隔,它们按照一定的顺序排列。
提示: 特别需要注意的是,即使你配置了系统提供的所有过滤器,这个过滤器链会很长,但是千万不要使用换行,否则它们不会正常工作, 容器甚至不能正常启动。 |
下面根据FilterChainProxy的配置来介绍各个过滤器的配置,各个过滤器的执行顺序如以上配置。
首先是通道处理过滤器,如果你需要使用HTTPS,这里我们就使用HTTP进行传输,所以不需要配置通道处理过滤器,然后是集成过滤器,配置如下:
2
3 class ="org.springframework.security.context.HttpSessionContextIntegrationFilter" />
httpSessionContextIntegrationFilter是集成过滤器的一个实现,在用户的一个请求过程中,用户的认证信息通过 SecurityContextHolder(使用ThreadLoacl实现)进行传递的,所有的过滤器都是通过 SecurityContextHolder来获取用户的认证信息,从而在一次请求中所有过滤器都能共享Authentication(认证),减少了 HttpRequest参数的传送,下面的代码是从安全上下文的获取Authentication对象的方法:
2
3 Authentication authentication = context.getAuthentication();
但是,ThreadLoacl不能跨越多个请求存在,所以,集成过滤器在请求开始时从Http会话中取出用户认证信息并创建一个 SecurityContextHolder将Authentication对象保存在其中,在请求结束之后,在从 SecurityContextHolder中获取Authentication对象并将其放回Http会话中,共下次请求使用,从而达到了跨越多个请求的目的。集成过滤器还有其它的实现,可以参考相关文档。
提示: 集成过滤器必须在其它过滤器之前被使用。 |
logoutFilter(退出过滤器) ,退出登录操作:
2
3 class ="org.springframework.security.ui.logout.LogoutFilter" >
4
5 < constructor-arg value ="/index.jsp" />
6
7 < constructor-arg >
8
9 < list >
10
11 <!-- 实现了LogoutHandler接口(logout方法) -->
12
13 < ref bean ="rememberMeServices" />
14
15 < bean class ="org.springframework.security.ui.logout.SecurityContextLogoutHandler" />
16
17 </ list >
18
19 </ constructor-arg >
20
21 </ bean >