按照SpringSecurity的文档,我们可以使用namespace的配置方式(前篇中已经说明)。
但是,我们这里的需求有点蹊跷,就是通过spring context进行权限配置太不方便,你想想能让人家客户通过spring xml来配置权限吗?不能,坚决不能!所以,我就单步跟踪获取里面的东西(这种方法比直接看代码快点,而且可以知道里面的逻辑结构!)
那就开始吧:
1.配置FilterChainProxy:
SpringSecurity的验证过程是通过一系列的filter来实现的。
这种chain的设计模式比较经典,可以说相当经典!
看看代码实现:
上篇中说过,默认的配置要求<filter-name>springSecurityFilterChain</filter-name>,那这个springSecurityFilterChain是怎么来用的呢?
public class DelegatingFilterProxy extends GenericFilterBean {
... ... ...
protected void initFilterBean() throws ServletException {
// If no target bean name specified, use filter name.
if (this.targetBeanName == null) {
this.targetBeanName = getFilterName();
}
// Fetch Spring root application context and initialize the delegate early,
// if possible. If the root application context will be started after this
// filter proxy, we'll have to resort to lazy initialization.
synchronized (this.delegateMonitor) {
WebApplicationContext wac = findWebApplicationContext();
if (wac != null) {
this.delegate = initDelegate(wac);
}
}
}
.....
}
不用说,你会猜到我们没有配置过targetBeanName这个属性,所以,就有了this.targetBeanName = getFilterName();这样的话就会配置FilterChainProxy了,因为FilterChainProxy在springContext中id是springSecurityFilterChain,所以我们要通过自己的数据库方式配置的话,就要琢磨这个FilterChainProxy了!
所以,首先做点这样的配置吧:
<beans:bean id="myFilterChain" class="org.springframework.security.web.FilterChainProxy" >
<filter-chain-map path-type="ant">
<filter-chain pattern="/login.jsp*" filters="none"/>
<filter-chain pattern="/**" filters="securityContextPersistenceFilter,
logoutFilter,
myUsernamePasswordAuthenticationFilter,
basicAuthenticationFilter,
requestCacheAwareFilter,
securityContextHolderAwareRequestFilter,
anonymousAuthenticationFilter,
sessionManagementFilter,
exceptionTranslationFilter,
filterSecurityInterceptor"/>
</filter-chain-map>
</beans:bean>
这个里面配置的id为myFilterChain,所以要在web.xml里面做相应配置:
<filter>
<filter-name>myFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
而且,尤为重要的是要配置上这些过滤器:
filter-chain pattern="/**" filters="securityContextPersistenceFilter,logoutFilter,
myUsernamePasswordAuthenticationFilter,
basicAuthenticationFilter,
requestCacheAwareFilter,
securityContextHolderAwareRequestFilter,
anonymousAuthenticationFilter,
sessionManagementFilter,
exceptionTranslationFilter,
filterSecurityInterceptor"
针对这些过滤器的用途,在spring security的文档中有详细描述,这里不多说了,在文档中的具体位置是7.2 FilterChainProxy,看看这一章就会有感觉了,不过绝知此事要躬行啊!
完成这些配置之后,我们就算是把入口给搭建好了!
鉴于文档篇幅,换到下篇接着说。