按照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,看看這一章就會有感覺了,不過絕知此事要躬行啊!
完成這些配置之后,我們就算是把入口給搭建好了!
鑒于文檔篇幅,換到下篇接著說。