前言
上一篇学习了下如何使用,并提出了一些问题,在看问题之前我们先了解下security是如何初始化Filters的
正文
Security中的Filters
Filter执行顺序.png
那么这些Filter从哪里来的?
从官网文档中我们了解到
Spring Security在内部维护一个过滤器链,其中每个过滤器都有特定的责任,并且根据需要哪些服务来添加或从配置中删除过滤器。
我们知道在需要使用servlet过滤器时,必须要在web.xml中声明,否则将不会生效。但是如果如上图所示这么多的filter不可能全部去配置,这样子太麻烦了,所以Spring提供了一个web.xml和应用程序上下文之间的链接DelegatingFilterProxy,在Security的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>
-
DelegatingFilterProxy类
DelegatingFilterProxy不是实际实现过滤器逻辑的类,而是将Filter的方法委托给从Spring应用程序上下文中获得的bean。
首先我们看一下这个Filter的init方法,该方法主要目的是找到在Spring中维护的目标Filter
public final void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
// Set bean properties from init parameters.
PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
if (!pvs.isEmpty()) {
try {
//将该类封装成spring特有的bean形式,方便spring维护
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
Environment env = this.environment;
if (env == null) {
env = new StandardServletEnvironment();
}
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, env));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
String msg = "Failed to set bean properties on filter '" +
filterConfig.getFilterName() + "': " + ex.getMessage();
logger.error(msg, ex);
throw new NestedServletException(msg, ex);
}
}
// Let subclasses do whatever initialization they like.
initFilterBean();
}
重点在这个initFilterBean()的实现,该方法主要完成了两个功能:
- 找到被代理类在Spring中配置的beanId并赋值给targetBeanName。
- 使用targetBeanName从Spring容器中找到具体被代理的类,并赋值给delegate
protected void initFilterBean() throws ServletException {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
// 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.
WebApplicationContext wac = findWebApplicationContext();
if (wac != null) {
this.delegate = initDelegate(wac);
}
}
}
}
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
String targetBeanName = getTargetBeanName();
Filter delegate = wac.getBean(targetBeanName, Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}
我们在来看一下doFilter()方法
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Lazily initialize the delegate if necessary.
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized (this.delegateMonitor) {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: " +
"no ContextLoaderListener or DispatcherServlet registered?");
}
delegateToUse = initDelegate(wac);
}
this.delegate = delegateToUse;
}
}
// Let the delegate perform the actual doFilter operation.
// 使用invokeDelegate方法,调用被代理的Filter的doFilter方法
invokeDelegate(delegateToUse, request, response, filterChain);
}
protected void invokeDelegate(
Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
delegate.doFilter(request, response, filterChain);
}
-
FilterChainProxy类
从官网文档中知道,Spring Security的Web基础结构只能用于委托给FilterChainProxy的一个实例,且这个实力的beanName叫springSecurityFilterChain,所以我们在源码中寻找springSecurityFilterChain是如何初始化的。
在WebSecurityConfiguration类中,发现了springSecurityFilterChain的初始化配置
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = webSecurityConfigurers != null
&& !webSecurityConfigurers.isEmpty();
if (!hasConfigurers) {
WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() {
});
webSecurity.apply(adapter);
}
return webSecurity.build();
}
webSecurity.build()方法初始化了整个Filter链,如图
springSecurityFilterChain初始化流程.png
这样整个FilterChainProxy就是初始化完成了,里面带有了第一张图所示的十三个Filter。
那么HttpSecurity什么时候把这些Filter加进去的呢,那么就要回到第一部分说的配置WebSecurityConfig类,我们重写了方法configure(HttpSecurity http),并且调用了一系列的链式方法,比如http.formLogin()
public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {
return getOrApply(new FormLoginConfigurer<>());
}
public FormLoginConfigurer() {
super(new UsernamePasswordAuthenticationFilter(), null);
usernameParameter("username");
passwordParameter("password");
}
这样Configurer加入进来了,在调用Configurer的configure方法时Filter也就初始化进去了。
贴一张官网的关系图
Filter对应关系图.png
-
自定义Filter
自定义的 Filter 建议继承 GenericFilterBean
HttpSecurity 有三个常用方法来配置:
- addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter)
在 beforeFilter 之前添加 filter - addFilterAfter(Filter filter, Class<? extends Filter> afterFilter)
在 afterFilter 之后添加 filter - addFilterAt(Filter filter, Class<? extends Filter> atFilter)
在 atFilter 相同位置添加 filter, 此 filter 不覆盖 filter
总结
这样子,我们就把整个Security的Filter初始化问题弄清楚了,只需要那么根据相应的Filter我们知道接下来的方向了。