SpringSecurity初始化过程

SpringSecurity初始化过程

SpringSecurity一定是被Spring加载的:

web.xml中通过ContextLoaderListener监听器实现初始化

<!--  初始化web容器--><!--设置配置文件的路径--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

而spring配置文件中又引入了security的配置文件

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.shaoby.service"></context:component-scan><bean name="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>//引入security配置文件<import resource="spring-security.xml"/>
</beans>

所以看ContextLoaderListener是如何加载的

Spring容器初始化

ContextLoaderListener中的configureAndRefreshWebApplicationContext方法

   protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {String configLocationParam;if (ObjectUtils.identityToString(wac).equals(wac.getId())) {configLocationParam = sc.getInitParameter("contextId");if (configLocationParam != null) {wac.setId(configLocationParam);} else {wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath()));}}wac.setServletContext(sc);//读取配置文件configLocationParam = sc.getInitParameter("contextConfigLocation");if (configLocationParam != null) {wac.setConfigLocation(configLocationParam);}ConfigurableEnvironment env = wac.getEnvironment();if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment)env).initPropertySources(sc, (ServletConfig)null);}this.customizeContext(sc, wac);//刷新容器,spring初始化的核心方法wac.refresh();}

refresh方法

    public void refresh() throws BeansException, IllegalStateException {synchronized(this.startupShutdownMonitor) {this.prepareRefresh();//创建bean工厂ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();this.prepareBeanFactory(beanFactory);try {this.postProcessBeanFactory(beanFactory);this.invokeBeanFactoryPostProcessors(beanFactory);this.registerBeanPostProcessors(beanFactory);this.initMessageSource();this.initApplicationEventMulticaster();this.onRefresh();this.registerListeners();this.finishBeanFactoryInitialization(beanFactory);this.finishRefresh();} catch (BeansException var9) {if (this.logger.isWarnEnabled()) {this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);}this.destroyBeans();this.cancelRefresh(var9);throw var9;} finally {this.resetCommonCaches();}}}

如何创建的bean工厂

spring通过loadBeanDefinitions方法完成初始化操作,它的实现方法可以通过xml配置文件或注解完成初始化

xml配置文件方法加载 XmlBeanDefinitionReader的loadBeanDefinitions方法中调用了doLoadBeanDefinitions方法
    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {try {//通过流读取xml文件Document doc = this.doLoadDocument(inputSource, resource);//注册beanint count = this.registerBeanDefinitions(doc, resource);if (this.logger.isDebugEnabled()) {this.logger.debug("Loaded " + count + " bean definitions from " + resource);}return count;} catch (BeanDefinitionStoreException var5) {throw var5;} catch (SAXParseException var6) {throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + var6.getLineNumber() + " in XML document from " + resource + " is invalid", var6);} catch (SAXException var7) {throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", var7);} catch (ParserConfigurationException var8) {throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, var8);} catch (IOException var9) {throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, var9);} catch (Throwable var10) {throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, var10);}}
解析xml文件
    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {if (delegate.isDefaultNamespace(root)) {NodeList nl = root.getChildNodes();for(int i = 0; i < nl.getLength(); ++i) {Node node = nl.item(i);if (node instanceof Element) {Element ele = (Element)node;if (delegate.isDefaultNamespace(ele)) {this.parseDefaultElement(ele, delegate);} else {//解析默认标签delegate.parseCustomElement(ele);}}}} else {//解析自定义标签delegate.parseCustomElement(root);}}private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {/如果是import标签,通过跟踪代码发现会去解析另一个配置文件,依次类推,直到没有import标签if (delegate.nodeNameEquals(ele, "import")) {this.importBeanDefinitionResource(ele);} else if (delegate.nodeNameEquals(ele, "alias")) {this.processAliasRegistration(ele);} else if (delegate.nodeNameEquals(ele, "bean")) {this.processBeanDefinition(ele, delegate);} else if (delegate.nodeNameEquals(ele, "beans")) {this.doRegisterBeanDefinitions(ele);}}

通过这段代码可以发现,spring会先解析默认标签,因此会先执行springsecurity的配置文件引入的操作

解析自定义标签
    public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {//获取标签String namespaceUri = this.getNamespaceURI(ele);if (namespaceUri == null) {return null;} else {//解析自定义标签,获得能解析该标签的HandlerResolver解析器NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);if (handler == null) {this.error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);return null;} else {return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));}}}

springSecurity解析器SecurityNamespaceHandler

/**不同的标签交给不同的解析器去解析*/private void loadParsers() {this.parsers.put("ldap-authentication-provider", new LdapProviderBeanDefinitionParser());this.parsers.put("ldap-server", new LdapServerBeanDefinitionParser());this.parsers.put("ldap-user-service", new LdapUserServiceBeanDefinitionParser());this.parsers.put("user-service", new UserServiceBeanDefinitionParser());this.parsers.put("jdbc-user-service", new JdbcUserServiceBeanDefinitionParser());this.parsers.put("authentication-provider", new AuthenticationProviderBeanDefinitionParser());this.parsers.put("global-method-security", new GlobalMethodSecurityBeanDefinitionParser());this.parsers.put("authentication-manager", new AuthenticationManagerBeanDefinitionParser());this.parsers.put("method-security-metadata-source", new MethodSecurityMetadataSourceBeanDefinitionParser());if (ClassUtils.isPresent("org.springframework.security.web.FilterChainProxy", this.getClass().getClassLoader())) {this.parsers.put("debug", new DebugBeanDefinitionParser());this.parsers.put("http", new HttpSecurityBeanDefinitionParser());this.parsers.put("http-firewall", new HttpFirewallBeanDefinitionParser());this.parsers.put("filter-security-metadata-source", new FilterInvocationSecurityMetadataSourceParser());this.parsers.put("filter-chain", new FilterChainBeanDefinitionParser());this.filterChainMapBDD = new FilterChainMapBeanDefinitionDecorator();this.parsers.put("client-registrations", new ClientRegistrationsBeanDefinitionParser());}if (ClassUtils.isPresent("org.springframework.messaging.Message", this.getClass().getClassLoader())) {this.parsers.put("websocket-message-broker", new WebSocketMessageBrokerSecurityBeanDefinitionParser());}}

http标签的解析,HttpSecurityBeanDefinitionParser

    public BeanDefinition parse(Element element, ParserContext pc) {CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), pc.extractSource(element));pc.pushContainingComponent(compositeDef);//注册FilterChainProxyregisterFilterChainProxyIfNecessary(pc, pc.extractSource(element));//拿到FilterChainProxyBeanDefinition listFactoryBean = pc.getRegistry().getBeanDefinition("org.springframework.security.filterChains");List<BeanReference> filterChains = (List)listFactoryBean.getPropertyValues().getPropertyValue("sourceList").getValue();//将过滤器放到filterChains中filterChains.add(this.createFilterChain(element, pc));pc.popAndRegisterContainingComponent();return null;}private BeanReference createFilterChain(Element element, ParserContext pc) {boolean secured = !"none".equals(element.getAttribute("security"));if (!secured) {if (!StringUtils.hasText(element.getAttribute("pattern")) && !StringUtils.hasText("request-matcher-ref")) {pc.getReaderContext().error("The 'security' attribute must be used in combination with the 'pattern' or '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 this.createSecurityFilterChainBean(element, pc, Collections.emptyList());} else {BeanReference portMapper = this.createPortMapper(element, pc);BeanReference portResolver = this.createPortResolver(portMapper, pc);ManagedList<BeanReference> authenticationProviders = new ManagedList();BeanReference authenticationManager = this.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());httpBldr.setLogoutHandlers(authBldr.getLogoutHandlers());httpBldr.setEntryPoint(authBldr.getEntryPointBean());httpBldr.setAccessDeniedHandler(authBldr.getAccessDeniedHandlerBean());httpBldr.setCsrfIgnoreRequestMatchers(authBldr.getCsrfIgnoreRequestMatchers());authenticationProviders.addAll(authBldr.getProviders());List<OrderDecorator> unorderedFilterChain = new ArrayList();unorderedFilterChain.addAll(httpBldr.getFilters());unorderedFilterChain.addAll(authBldr.getFilters());unorderedFilterChain.addAll(this.buildCustomFilterList(element, pc));unorderedFilterChain.sort(new OrderComparator());this.checkFilterChainOrder(unorderedFilterChain, pc, pc.extractSource(element));List<BeanMetadataElement> filterChain = new ManagedList();Iterator var13 = unorderedFilterChain.iterator();while(var13.hasNext()) {OrderDecorator od = (OrderDecorator)var13.next();filterChain.add(od.bean);}return this.createSecurityFilterChainBean(element, pc, filterChain);}}
//注册FilterChainProxy
static void registerFilterChainProxyIfNecessary(ParserContext pc, Object source) {if (!pc.getRegistry().containsBeanDefinition("org.springframework.security.filterChainProxy")) {BeanDefinition listFactoryBean = new RootBeanDefinition(ListFactoryBean.class);listFactoryBean.getPropertyValues().add("sourceList", new ManagedList());pc.registerBeanComponent(new BeanComponentDefinition(listFactoryBean, "org.springframework.security.filterChains"));BeanDefinitionBuilder fcpBldr = BeanDefinitionBuilder.rootBeanDefinition(FilterChainProxy.class);fcpBldr.getRawBeanDefinition().setSource(source);fcpBldr.addConstructorArgReference("org.springframework.security.filterChains");fcpBldr.addPropertyValue("filterChainValidator", new RootBeanDefinition(DefaultFilterChainValidator.class));BeanDefinition fcpBean = fcpBldr.getBeanDefinition();pc.registerBeanComponent(new BeanComponentDefinition(fcpBean, "org.springframework.security.filterChainProxy"));//添加别名springSecurityFilterChainpc.getRegistry().registerAlias("org.springframework.security.filterChainProxy", "springSecurityFilterChain");}}

到这可以看到所有的过滤器被放到filterChain中

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/42947.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

sql注入问题批量处理

问题&#xff1a;SQL注入修改&#xff0c;历史代码全是${};无法修改的比如表名&#xff0c;列名&#xff0c;动态排序之类的不改&#xff0c;其他的都要修改完成 背景&#xff1a;新公司第一个任务就是SQL注入的修改&#xff0c;历史sql全部都是${},一个个调整不太合适只能批量…

机场的出租车问题折线图

分析并可视化机场离场车辆数数据 本文将详细介绍如何使用Python的正则表达式库re和绘图库matplotlib对机场离场车辆数数据进行分析和可视化。以下是具体步骤和代码实现。 数据资源&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1rU-PRhrVSXq-8YdR6obc6Q?pwd1234 提…

Android C++系列:Linux常用函数和工具

1. 时间函数 1.1 文件访问时间 #include <sys/types.h> #include <utime.h> int utime (const char *name, const struct utimebuf *t); 返回:若成功则为 0,若出错则为- 1如果times是一个空指针,则存取时间和修改时间两者都设置为当前时间; 如果times是非空指针…

一个python文件实现openai 转换请求转换成 ollama

最近在微软开源了GraphRAG,项目&#xff0c;是一个很棒的项目&#xff0c;本着研究学习的态度下载了该项目测试&#xff0c;发现目前只可以使用openai chat gpt,或azure open chat gpt,也就是说意味着资料要上传到第三方网站处理&#xff0c;为了本地的ollama也可以使用特意开发…

轮播图案例

丐版轮播图 <!DOCTYPE html> <html lang"zh-cn"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title> 基础轮播图 banner 移入移出</t…

6000字以上论文参考:基于Java+SpringMvc+Vue技术的实验室管理系统设计与实现

可参考&#xff1a;基于JavaSpringMvcVue技术的实验室管理系统设计与实现&#xff08;6000字以上论文参考&#xff09;-CSDN博客 论文参考&#xff1a;

【python】字典、列表、集合综合练习

1、练习1(字典) 字典dic,dic {‘k1’:‘v1’, ‘k2’: ‘v2’, ‘k3’: [11,22,33]} (1). 请循环输出所有的key dic {"k1": "v1", "k2": "v2", "k3": [11, 22, 33]} for k in dic.keys():print(k)k1 k2 k3(2). 请循环输…

2024 WAIC|第四范式胡时伟分享通往AGI之路:行业大模型汇聚成海

7月4日&#xff0c;2024世界人工智能大会&#xff08;WAIC&#xff09;正式开幕。此次大会围绕核心技术、智能终端、应用赋能等板块展开&#xff0c;展览规模、参展企业数均达历史最高。第四范式受邀参展&#xff0c;集中展示公司十年来在行业大模型产业应用方面的实践。在当天…

【知网CNKI-注册安全分析报告】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…

dockerfile里的copy只能使用相对路径吗?

在 Dockerfile 中&#xff0c;COPY 指令既可以使用相对路径&#xff0c;也可以使用绝对路径&#xff08;但绝对路径的使用方式和上下文有关&#xff09;。不过&#xff0c;在实践中&#xff0c;你通常会看到使用相对路径&#xff0c;因为 Dockerfile 的构建上下文&#xff08;b…

NewspaceGPT带你玩系列之【Song Maker】

目录 注册一个账号&#xff0c;用qq邮箱&#xff0c;然后登录选一个可用的Plus&#xff0c;不要选3.5探索GPT今天的主角是【Song Maker】翻译一下用汉语吧我写词。你谱曲和其他伴奏&#xff0c;例子&#xff1a; 摇滚&#xff0c;忧伤&#xff0c;吉他&#xff0c;鼓&#xff0…

聊一聊Oracle的空间计算函数SDO_NN

网上对这个函数介绍的很少&#xff0c;对使用上也很模糊&#xff0c;我来补充一下&#xff0c;让大家了解一下这个函数 from test1 y, test2 p where SDO_NN(p.geom,y.geom,sdo_num_res1, 0.5 )TRUE; 上面这个表达式的含义也就是说在test2中找到一个距离test1很近的&#x…

Android约束布局的概念与属性(1)

目录 1&#xff0e;相对定位约束2&#xff0e;居中和偏移约束 约束布局&#xff08;ConstraintLayout&#xff09;是当前Android Studio默认的布局方式&#xff0c;也是最灵活的一种布局方式。约束布局推荐使用所见即所得的模式进行布局&#xff0c;约束布局的大部分布局可以通…

超详细的 Linux 环境下 Anaconda 安装与使用教程

超详细的 Linux 环境下 Anaconda 安装与使用教程 前言 在数据科学和机器学习领域&#xff0c;Anaconda 是一个非常受欢迎的发行版&#xff0c;提供了许多常用的包和工具。本文将详细介绍如何在 Linux 系统上安装和配置 Anaconda 环境&#xff0c;并展示如何高效地使用它。 一…

CentOS7下安装Doris

Doris简介 Apache Doris 是一款基于 MPP 架构的高性能、实时的分析型数据库&#xff0c;以高效、简单、统一的特点被人们所熟知&#xff0c;仅需亚秒级响应时间即可返回海量数据下的查询结果&#xff0c;不仅可以支持高并发的点查询场景&#xff0c;也能支持高吞吐的复杂分析场…

从0到1搭建个性化推送引擎:百数教学带你掌握核心技术

百数低代码的推送提醒功能允许用户高度自定义提醒规则&#xff0c;支持多种提醒方式&#xff08;如钉钉、企业微信、微信、短信、语音、邮件等&#xff09;&#xff0c;以满足不同场景下的需求。 通过预设字段和模板&#xff0c;用户可以快速编辑提醒内容&#xff0c;减少重复…

BaseServlet的封装

创建BaseServlet的必要性 如果不创建BaseServlet&#xff0c;现在我们只要实现一个功能&#xff0c;我们就需要创建一个servlet! 例如:用户模块(登录&#xff0c;注册&#xff0c;退出录&#xff0c;激活&#xff0c;发送邮件等等功能) 也就是说&#xff0c;我们必须要创建一…

idea无法实力化id

解决&#xff1a;https://blog.csdn.net/qq_41264674/article/details/83409810?ops_request_misc&request_id&biz_id102&utm_termSerializable%E4%B8%8D%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E5%AE%9E%E5%8A%9B%E5%8C%96id&utm_mediumdistribute.pc_search_…

java-数据结构与算法-02-数据结构-03-递归

1. 概述 定义 计算机科学中&#xff0c;递归是一种解决计算问题的方法&#xff0c;其中解决方案取决于同一类问题的更小子集 In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances…

IT项目经理转行大模型,项目经理的进来,你想知道的都在这里非常详细

大模型&#xff08;如人工智能、机器学习和深度学习模型&#xff09;可以通过提供数据驱动的决策支持、自动化流程和预测分析来赋能IT项目经理。这些工具可以帮助项目经理更有效地管理项目&#xff0c;预测潜在的风险&#xff0c;并提高项目成功的可能性。以下是IT项目经理如何…