本文分析是基于Spring Security(以后简称SS)的3.1.3版本,不同版本可能稍有不同。
SS设计架构是基于Filter过滤器思想,理解SS Filter实现机制对深度使用好SS大有帮助。整个SS Filter实现机理可用一张图清晰表述出来。
如图,对于用户的HTTP请求,首先经过Servlet容器定义的Filter过滤器链进行前处理,然后到达真正进行业务请求处理的Servlet,最后沿反方向通过Filter过滤器链完成后处理后,返回给用户。
Servlet容器级的过滤器在web.xml中定义,由图可看出,web.xml定义了一个特殊的过滤器org.springframework.web.filter.DelegatingFilterProxy(在spring-web jar包中定义),由它启动Spring容器级的过滤器。通过指定过滤器名为springSecurityFilterChain,以及SS的配置文件,该过滤器将调用org.springframework.security.web.FilterChainProxy(spring-security-web jar包中定义),启动SS定义的Spring容器级负责安全的过滤器链。DelegatingFilterProxy在web.xml的定义通常如下:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy<filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain<filter-name>
<url-pattern>/*<url-pattern>
<filter-mapping>
SS最基本配置要素(通常在applicationContext-security.xml中)如下:
<http>
<form-login />
<logout/>
<http>
该配置定义了form表单username/password验证登录方式,登出机制。此时,SS 3.1将注册11个filter形成filter过滤器链来实现系统的安全处理。这11个filter的逻辑顺序如下:
org.springframework.security.web.context.SecurityContextPersistenceFilter
org.springframework.security.web.session.ConcurrentSessionFilter
org.springframework.security.web.authentication.logout.LogoutFilter
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
org.springframework.security.web.savedrequest.RequestCacheAwareFilter
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
org.springframework.security.web.session.SessionManagementFilter
org.springframework.security.web.access.ExceptionTranslationFilter
org.springframework.security.web.access.intercept.FilterSecurityInterceptor
每个过滤器都将提供特定的功能,其中比较重要的包括UsernamePasswordAuthenticationFilter 负责表单认证方式登录处理,LogoutFilter负责登出处理,SessionManagementFilter、ConcurrentSessionFilter负责SS session方面的管理和控制,FilterSecurityInterceptor处理权限验证等。
SS 3.1总共提供了21个filter,这些filter在SS filter过滤器链中的缺省顺序由org.springframework.security.config.http.SecurityFilters枚举类型定义。通过filter机制,SS实现了安全认证和授权等安全相关工作。用户通过配置文件,可以插入、替换或去除已知的filter,搭配自己的SS filter过滤器链,从而实现满足自己特定应用需求的安全处理。