1、对 SpringSecurity初始化时的几个疑问
通过对前边一个请求流转的分析,我们知道一个请求要想到达服务端Servlet需要经过n多个
拦截器处理,请求处理流程如下所示:
对于一个请求到来后会通过FilterChainProxy来匹配一个对应的过滤器链来处理该请求,但这里
有几个疑问,即:
1)为什么在web.xml定义的过滤器的名称必须是 springSecurityFilterChain?
2)FilterChainProxy 对象是什么时候注入到SpringIOC容器的?
3)过滤器链和对应的各个过滤器是什么时候创建和注入FilterChainProxy 的?
4)怎么把自定义的过滤器添加到过滤器链中?
5)请求和过滤器的匹配规则是什么?
2、解析 SpringSecurity 配置文件的过程
2.1、解析前的处理
首先 spring web项目启动时,首先会处理 web.xml 中配置的监听器 ContextLoaderListener
然后会执行对应的 initWebApplicationContext 方法去初始化spring容器
最后 configureAndRefreshWebApplicationContext 方法中调用 refresh() 方法完成spring
容器的初始化,并启动spring。
refresh() 方法代码如下:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
/**
* 前戏,做容器刷新前的准备工作
* 1、设置容器的启动时间
* 2、设置活跃状态为true
* 3、设置关闭状态为false
* 4、获取Environment对象,并加载当前系统的属性值到Environment对象中
* 5、准备监听器和事件的集合对象,默认为空的集合
*/
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 创建容器对象:DefaultListableBeanFactory
// 加载xml配置文件的属性值到当前工厂中,最重要的就是BeanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// beanFactory的准备工作,对各种属性进行填充
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 子类覆盖方法做额外的处理,此处我们自己一般不做任何扩展工作,但是可以查看web中的代码,是有具体实现的
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 调用各种beanFactory处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册bean处理器,这里只是注册功能,真正调用的是getBean方法
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 为上下文初始化message源,即不同语言的消息体,国际化处理,在springmvc的时候通过国际化的代码重点讲
initMessageSource();
// Initialize event multicaster for this context.
// 初始化事件监听多路广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 留给子类来初始化其他的bean
onRefresh();
// Check for listener beans and register them.
// 在所有注册的bean中查找listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化剩下的单实例(非懒加载的)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 为防止bean资源占用,在异常处理中,销毁已经在前面过程中生成的单件bean
destroyBeans();
// Reset 'active' flag.
// 重置active标志
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
我们要看配置文件的加载解析需要进入obtainFreshBeanFactory()方法中。
继续进入到AbstractRefreshableApplicationContext.refreshBeanFactory() 方法中,
读取配置文件的功能是在方法 loadBeanDefinitions(beanFactory) 中完成的,
loadBeanDefinitions(beanFactory) 在类AbstractRefreshableApplicationContext中是
一个抽象方法,由子类实现;xml配置文件解析需要看 AbstractXmlApplicationContext
类中的方法,进入 loadBeanDefinitions方法
一直往下点进去相关方法,最终 加载xml 配置文件是在
XmlBeanDefinitionReader.loadBeanDefinitions 方法中执行的,
具体的配置文件解析是在方法 doLoadBeanDefinitions 中进行的
1
2.2、配置文件解析过程
在上面的步骤基础上我们进入registerBeanDefinitions方法中来看看是如何具体实现配置文
件的解析操作。
进入 registerBeanDefinitions 方法
然后进入 documentReader.registerBeanDefinitions ,该 registerBeanDefinitions 是一个接口
方法,直接进入其的默认实现类 DefaultBeanDefinitionDocumentReader 中
继续进入 doRegisterBeanDefinitions 方法
继续,进入解析root节点方法 parseBeanDefinitions
parseDefaultElement方法会完成Spring中提供的默认方法解析,具体如下:
而SpringSecurity的解析是先进入import中,然后进入到parseCustomElement()方法来解析。
1
3、SpringSecurity 解析器 SecurityNamespaceHandler
SpringSecurity 配置问价 如下:
在 SpringSecurity 配置文件中,配置了2个最外层标签,即 <security:http> 和
<security:authentication-manager>,那么第一次调用方法 parseCustomElement 时,
传入的参数 ele 应该是 security:http
SpringSecurity 的每一个标签都有一个解析器与其对应
进入NamespaceHndler.init()方法
NamespaceHndler 是一个spring接口,他有许多实现类,这里我们应该选择 SpringSecurity
提供的实现类 SecurityNamespaceHandler
在SecurityNamespaceHandler中的 parsers中保存的就是 节点对应的解析器。
4、Http标签解析
由上边的分析可以发现,http标签的解析是由解析器 HttpSecurityBeanDefinitionParser 完成
的,HttpSecurityBeanDefinitionParser 实现了接口 BeanDefinitionParser,而 接口
BeanDefinitionParser 是由spring 提供的,(题外话:到这里是不是渐渐明白了SpringSecurity
与spring整合的逻辑?)
下面进入 HttpSecurityBeanDefinitionParser 的parse 方法看下 http标签解析的逻辑
@Override
public BeanDefinition parse(Element element, ParserContext pc) {
// CompositeComponentDefinition 保存内嵌的BeanDefinition
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(
element.getTagName(), pc.extractSource(element));
// compositeDef定义保存在了 父容器中
pc.pushContainingComponent(compositeDef);
// 完成FilterChainProxy的注册
registerFilterChainProxyIfNecessary(pc, pc.extractSource(element));
// Obtain the filter chains and add the new chain to it
BeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition(
BeanIds.FILTER_CHAINS);
List<BeanReference> filterChains = (List<BeanReference>) listFactoryBean
.getPropertyValues().getPropertyValue("sourceList").getValue();
// createFilterChain(element, pc) 创建对应的过滤器并添加到了filterChains这个过滤器链中
filterChains.add(createFilterChain(element, pc));
pc.popAndRegisterContainingComponent();
return null;
}
上边代码的几个关键点:
1)CompositeComponentDefinition保存配置文件中的嵌套的BeanDefinition信息
2)完成了FilterChainProxy的注册
3)完成了处理请求的过滤器和过滤器链的处理
1
5、FilterChainProxy的注册
通过上边的分析我们可以进入 registerFilterChainProxyIfNecessary()方法来查看
FilterChainProxy的注册过程
SpringSecurity在BeanId中定义了相关的固定beanId值。
public abstract class BeanIds {
private static final String PREFIX = "org.springframework.security.";
/**
* The "global" AuthenticationManager instance, registered by the
* <authentication-manager> element
*/
public static final String AUTHENTICATION_MANAGER = PREFIX + "authenticationManager";
/** External alias for FilterChainProxy bean, for use in web.xml files */
public static final String SPRING_SECURITY_FILTER_CHAIN = "springSecurityFilterChain";
public static final String CONTEXT_SOURCE_SETTING_POST_PROCESSOR = PREFIX
+ "contextSettingPostProcessor";
public static final String USER_DETAILS_SERVICE = PREFIX + "userDetailsService";
public static final String USER_DETAILS_SERVICE_FACTORY = PREFIX
+ "userDetailsServiceFactory";
public static final String METHOD_ACCESS_MANAGER = PREFIX
+ "defaultMethodAccessManager";
public static final String FILTER_CHAIN_PROXY = PREFIX + "filterChainProxy";
public static final String FILTER_CHAINS = PREFIX + "filterChains";
public static final String METHOD_SECURITY_METADATA_SOURCE_ADVISOR = PREFIX
+ "methodSecurityMetadataSourceAdvisor";
public static final String EMBEDDED_APACHE_DS = PREFIX
+ "apacheDirectoryServerContainer";
public static final String CONTEXT_SOURCE = PREFIX + "securityContextSource";
public static final String DEBUG_FILTER = PREFIX + "debugFilter";
}
6、创建过滤器
SpringSecurity中默认过滤器是在 HttpSecurityBeanDefinitionParser.parse()方法中执行下边一
行代码来创建并注入到连接器链的的,即:
filterChains.add(this.createFilterChain(element, pc));
进入 createFilterChain 方法
private BeanReference createFilterChain(Element element, ParserContext pc) {
// 判断是否需要Security拦截
boolean secured = !OPT_SECURITY_NONE.equals(element.getAttribute(ATT_SECURED));
if (!secured) {
// 如果没配置pattern属性并且配置了request-matcher-ref为空 添加错误信息
if (!StringUtils.hasText(element.getAttribute(ATT_PATH_PATTERN)) && !StringUtils.hasText(ATT_REQUEST_MATCHER_REF)) {
pc.getReaderContext().error("The '" + ATT_SECURED + "' attribute must be used in combination with" + " the '" + ATT_PATH_PATTERN + "' or '" + ATT_REQUEST_MATCHER_REF + "' attributes.", pc.extractSource(element));
}
for (int n = 0; n < element.getChildNodes().getLength(); n++) {
// 如果有子节点则添加错误信息
if (element.getChildNodes().item(n) instanceof Element) {
pc.getReaderContext().error("If you are using <http> to define an unsecured pattern, " + "it cannot contain child elements.", pc.extractSource(element));
}
}
// 创建过滤器链
return createSecurityFilterChainBean(element, pc, Collections.emptyList());
}
// portMapper、portResolver主要提供给SSL相关类使用
final BeanReference portMapper = createPortMapper(element, pc);
final BeanReference portResolver = createPortResolver(portMapper, pc);
// 新建一个空的authenticationProviders集合
ManagedList<BeanReference> authenticationProviders = new ManagedList<BeanReference>();
// 通过空的authenticationProviders集合产生一个AuthenticationManager的bean定义
BeanReference authenticationManager = createAuthenticationManager(element, pc, authenticationProviders);
// 是否全采用默认配置
boolean forceAutoConfig = isDefaultHttpConfig(element);
// 看下面
HttpConfigurationBuilder httpBldr = new HttpConfigurationBuilder(element, forceAutoConfig, pc, portMapper, portResolver, authenticationManager);
// 看下面
AuthenticationConfigBuilder authBldr = new AuthenticationConfigBuilder(element, forceAutoConfig, pc, httpBldr.getSessionCreationPolicy(), httpBldr.getRequestCache(), authenticationManager, httpBldr.getSessionStrategy(), portMapper, portResolver, httpBldr.getCsrfLogoutHandler());
// 配置logoutHandlers
httpBldr.setLogoutHandlers(authBldr.getLogoutHandlers());
httpBldr.setEntryPoint(authBldr.getEntryPointBean());
httpBldr.setAccessDeniedHandler(authBldr.getAccessDeniedHandlerBean());
// 向AuthenticationProviders中添加provider
authenticationProviders.addAll(authBldr.getProviders());
List<OrderDecorator> unorderedFilterChain = new ArrayList<OrderDecorator>();
// 向FilterChain链中添加filters
unorderedFilterChain.addAll(httpBldr.getFilters());
unorderedFilterChain.addAll(authBldr.getFilters());
// 添加自定义的Filter,也就是custom-filter标签定义的Filter
unorderedFilterChain.addAll(buildCustomFilterList(element, pc));
// 对过滤器进行排序
Collections.sort(unorderedFilterChain, new OrderComparator());
// 校验过滤器是否有效
checkFilterChainOrder(unorderedFilterChain, pc, pc.extractSource(element));
// The list of filter beans
List<BeanMetadataElement> filterChain = new ManagedList<BeanMetadataElement>();
for (OrderDecorator od : unorderedFilterChain) {
filterChain.add(od.bean);
}
// 创建SecurityFilterChain
return createSecurityFilterChainBean(element, pc, filterChain);
}
先看下HttpConfigurationBuilder的构造方法
public HttpConfigurationBuilder(Element element, boolean addAllAuth, ParserContext pc, BeanReference portMapper, BeanReference portResolver, BeanReference authenticationManager) {
this.httpElt = element;
this.addAllAuth = addAllAuth;
this.pc = pc;
this.portMapper = portMapper;
this.portResolver = portResolver;
this.matcherType = MatcherType.fromElement(element);
// 获取子标签intercept-url
interceptUrls = DomUtils.getChildElementsByTagName(element, Elements.INTERCEPT_URL);
for (Element urlElt : interceptUrls) {
// 判断子标签intercept-url是否配置了filters属性
// 如果配置了filters属性添加错误消息,因为Security已经不再支持filters属性了
if (StringUtils.hasText(urlElt.getAttribute(ATT_FILTERS))) {
pc.getReaderContext().error("The use of \"filters='none'\" is no longer supported. Please define a" + " separate <http> element for the pattern you want to exclude and use the attribute" + " \"security='none'\".", pc.extractSource(urlElt));
}
}
// 获取标签create-session属性
String createSession = element.getAttribute(ATT_CREATE_SESSION);
if (StringUtils.hasText(createSession)) {
sessionPolicy = createPolicy(createSession);
} else {
// 默认策略
sessionPolicy = SessionCreationPolicy.IF_REQUIRED;
}
// 创建一系列过滤器
createCsrfFilter();
createSecurityContextPersistenceFilter();
createSessionManagementFilters();
createWebAsyncManagerFilter();
createRequestCacheFilter();
createServletApiFilter(authenticationManager);
createJaasApiFilter();
createChannelProcessingFilter();
createFilterSecurityInterceptor(authenticationManager);
createAddHeadersFilter();
}
然后进入AuthenticationConfigBuilder中来查看,发现其实也创建了很多的过滤器
public AuthenticationConfigBuilder(Element element, boolean forceAutoConfig, ParserContext pc, SessionCreationPolicy sessionPolicy, BeanReference requestCache, BeanReference authenticationManager, BeanReference sessionStrategy, BeanReference portMapper, BeanReference portResolver, BeanMetadataElement csrfLogoutHandler) {
this.httpElt = element;
this.pc = pc;
this.requestCache = requestCache;
// 是否自动配置
autoConfig = forceAutoConfig | "true".equals(element.getAttribute(ATT_AUTO_CONFIG));
// 是否允许session
this.allowSessionCreation = sessionPolicy != SessionCreationPolicy.NEVER && sessionPolicy != SessionCreationPolicy.STATELESS;
this.portMapper = portMapper;
this.portResolver = portResolver;
this.csrfLogoutHandler = csrfLogoutHandler;
// 创建一系列过滤器
createAnonymousFilter();
createRememberMeFilter(authenticationManager);
createBasicFilter(authenticationManager);
createFormLoginFilter(sessionStrategy, authenticationManager);
createOpenIDLoginFilter(sessionStrategy, authenticationManager);
createX509Filter(authenticationManager);
createJeeFilter(authenticationManager);
createLogoutFilter();
createLoginPageFilterIfNeeded();
createUserDetailsServiceFactory();
createExceptionTranslationFilter();
}
最后再看下 HttpSecurityBeanDefinitionParser.createSecurityFilterChainBean 方法
在 createSecurityFilterChainBean 方法中创建请求匹配器,并把过滤器链注册到spring容器中
createSecurityFilterChainBean 方法代码如下:
private BeanReference createSecurityFilterChainBean(Element element, ParserContext pc, List<?> filterChain) {
String requestMatcherRef = element.getAttribute("request-matcher-ref");
String filterChainPattern = element.getAttribute("pattern");
Object filterChainMatcher;
//创建请求匹配器
if (StringUtils.hasText(requestMatcherRef)) {
if (StringUtils.hasText(filterChainPattern)) {
pc.getReaderContext().error("You can't define a pattern and a request-matcher-ref for the same filter chain", pc.extractSource(element));
}
filterChainMatcher = new RuntimeBeanReference(requestMatcherRef);
} else if (StringUtils.hasText(filterChainPattern)) {
filterChainMatcher = MatcherType.fromElement(element).createMatcher(pc, filterChainPattern, (String)null);
} else {
//匹配所有的请求
filterChainMatcher = new RootBeanDefinition(AnyRequestMatcher.class);
}
//拦截器链 DefaultSecurityFilterChain 绑定了类型
BeanDefinitionBuilder filterChainBldr = BeanDefinitionBuilder.rootBeanDefinition(DefaultSecurityFilterChain.class);
//给拦截器链绑定请求匹配器
filterChainBldr.addConstructorArgValue(filterChainMatcher);
filterChainBldr.addConstructorArgValue(filterChain);
BeanDefinition filterChainBean = filterChainBldr.getBeanDefinition();
String id = element.getAttribute("name");
if (!StringUtils.hasText(id)) {
id = element.getAttribute("id");
if (!StringUtils.hasText(id)) {
id = pc.getReaderContext().generateBeanName(filterChainBean);
}
}
//将拦截器链注入到spring 容器中
pc.registerBeanComponent(new BeanComponentDefinition(filterChainBean, id));
return new RuntimeBeanReference(id);
}