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中
相关文章:

SpringSecurity初始化过程
SpringSecurity初始化过程 SpringSecurity一定是被Spring加载的: web.xml中通过ContextLoaderListener监听器实现初始化 <!-- 初始化web容器--><!--设置配置文件的路径--><context-param><param-name>contextConfigLocation</param-…...

Python爬取股票信息-并进行数据可视化分析,绘股票成交量柱状图
为了使用Python爬取股票信息并进行数据可视化分析,我们可以使用几个流行的库:requests 用于网络请求,pandas 用于数据处理,以及 matplotlib 或 seaborn 用于数据可视化。 步骤 1: 安装必要的库 首先,确保安装了以下P…...

秋招突击——7/4——复习{}——新作{最长公共子序列、编辑距离、买股票最佳时机、跳跃游戏}
文章目录 引言复习新作1143-最长公共子序列个人实现 参考实现编辑距离个人实现参考实现 贪心——买股票的最佳时机个人实现参考实现 贪心——55-跳跃游戏个人实现参考做法 总结 引言 昨天主要是面试,然后剩下的时间都是用来对面试中不会的东西进行查漏补缺ÿ…...

udp发送数据如果超过1个mtu时,抓包所遇到的问题记录说明
最近在测试Syslog udp发送相关功能,测试环境是centos udp头部的数据长度是2个字节,最大传输长度理论上是65535,除去头部这些字节,可以大概的说是64k。 写了一个超过64k的数据(随便用了一个7w字节的buffer)发送demo,打…...

电子电气架构 --- 智能座舱万物互联
我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗你的人和事,多看一眼都是你的不对。非必要不费力证明自己,无利益不试图说服别人,是精神上的节…...

笔记本电脑内存不够
笔记本电脑内存不够是众多笔记本用户面临的常见问题,尤其是对于一些需要处理大型文件或者运行复杂软件的用户,这个问题可能会严重影响笔记本的使用体验。那么,我们应该如何解决笔记本电脑内存不够的问题呢?本文将从几个方面进行详…...

Vue项目使用mockjs模拟后端接口
文章目录 操作步骤1. 安装 mockjs 和 vite-plugin-mock2. 安装 axios3. 创建mock路径4. 配置 viteMockConfig5. 编写第一个mock接口6. 创建 createProdMockServer7. 配置 axios8. 编写请求接口9. 在页面中使用 操作步骤 1. 安装 mockjs 和 vite-plugin-mock vite-plugin-mock …...

Linux下使用arping检测IP地址是否冲突
arping简介 在Linux中,arping是一个用来发送ARP请求到一个相邻主机的工具,通常用于检测网络上的IP地址冲突。 使用arping检测IP地址是否冲突的方法 例1:使用如下命令检测10.206.216.95是否冲突 (使用-I参数指定网络接口) # arping -I eth…...

为什么 npm run serve 正常,npm run build 就报错:digital envelope routines::unsupported
这个错误通常与 Node.js 版本和使用的加密算法有关。让我解释一下原因和可能的解决方案: 错误原因 这个错误(“error:0308010C:digital envelope routines::unsupported”)通常发生在以下情况: 使用较新版本的 Node.js…...

模电基础 - 简介
目录 零 .简介 一. 学习方法 二. 教材推荐 三. 总结 零 .简介 “模电”即模拟电子技术,是电子信息工程、电气工程及其自动化等相关专业的一门关键基础课程。 首先,在半导体器件方面,二极管是一种具有单向导电性的器件,由 P 型…...

uniapp中实现瀑布流 短视频页面展示
直接上干货 第一部分为结构 <swiper class"list" :currentindex change"swiperchange" scrolltolower"onReachBottom"><swiper-item style"overflow: scroll;" v-for"(item,index) in 2" :key"index"&g…...

python-开关灯(赛氪OJ)
[题目描述] 假设有 N 盏灯(N 为不大于 5000 的正整数),从 1 到到 N 按顺序依次编号,初始时全部处于开启状态;第一个人( 1 号)将灯全部关闭,第二个人( 2 号)将…...

基于改进高斯-拉普拉斯滤波器的一维时间序列平滑与降噪(MATLAB)
以图像处理为例,拉普拉斯算子是基于图像的二阶导数来找到边缘并搜索过零点,传统的拉普拉斯算子常产生双像素宽的边缘,对于较暗区域中的亮斑进行边缘检测时,拉普拉斯运算就会使其变得更亮。因此,与梯度算子一样…...

计算组的妙用!!页面权限控制
需求描述: 某些特殊的场景下,针对某页看板,需要进行数据权限卡控,但是又不能对全部的数据进行RLS处理,这种情况下可以利用计算组来解决这个需求。 实际场景 事实表包含产品维度和销售维度 两个维度属于同一公司下面的…...

Self-Instruct构造Prompt的例子
人工构造一批Prompt做种子。(Starting with a small seed set of human-written tasks)每次把一些种子后来生成的Prompt,放到Input里做few-shot examples,用LLM生成更多的Prompt;(Using the LLM to generat…...

友好前端vue脚手架
企业级后台集成方案vue-element-admin-CSDN博客在哔站学习,老师说可以有直接的脚手架(vue-element-admin)立马去搜索,找到了这博主这篇文章 介绍 | vue-element-admin 官方默认英文版: git clone https:/…...

SQL Server特性
一、创建表 在sql server中使用create table来创建新表。 create table Customers( id int primary key identity(1,1), name varchar(5) ) 该表名为Customers其中包含了2个字段,分别为id(主键)以及name。 1、数据类型 整数类型ÿ…...

华为HCIP Datacom H12-821 卷25
1.单选题 Smurf攻击一般使用以下哪种协议 A、TCP B、BGP C、ICMP D、DHCP 正确答案: C 解析: Smurf攻击是一种病毒攻击,以最初发动这种攻击的程序“Smurf”来命名。这种攻击方法结合使用了IP欺骗和ICMP回复方法使大量网络传输充斥目…...

如何在 Selenium Python 中解决验证码 | 2024 完整指南
由于在进行网络自动化时遇到验证码是让许多人感到不知所措的问题。这些验证码专为区分人类用户和自动化脚本而设计,对于使用Selenium进行网络爬虫或自动化任务而言,无疑是一个巨大的挑战。2024年的完全指南将为您提供全面的解决方案,帮助您高…...

ASCII码对照表【2024年汇总】
🍺ASCII相关文章汇总如下🍺: 🎈ASCII码对照表(255个ascii字符汇总)🎈🎈ASCII码对照表(Unicode 字符集列表)🎈🎈ASCII码对照表&#x…...

刷题之买股票的最佳时机(leetcode)
买股票的最佳时机 动态规划入门题。 最简单的模拟式解法: class Solution { public:int maxProfit(vector<int>& prices) {//也可以换一种思路,因为只交易一次,那么找出股票最便宜的时候买入,最贵的时候卖出ÿ…...

Apache Seata透过源码解决SeataAT模式整合Mybatis-Plus失去MP特性的问题
本文来自 Apache Seata官方文档,欢迎访问官网,查看更多深度文章。 本文来自 Apache Seata官方文档,欢迎访问官网,查看更多深度文章。 Apache Seata透过源码解决SeataAT模式整合Mybatis-Plus失去MP特性的问题 透过源码解决SeataAT…...

1.2 如何让机器说人话?万字长文回顾自然语言处理(NLP)的前世今生 —— 《带你自学大语言模型》系列
本系列目录 《带你自学大语言模型》系列部分目录及计划,完整版目录见:带你自学大语言模型系列 —— 前言 第一部分 走进大语言模型(科普向) 第一章 走进大语言模型 1.1 从图灵机到GPT,人工智能经历了什么࿱…...

【QT】按钮类控件
按钮类控件 按钮类控件1. PushButton2. Radio Button3. Check Box4. Tool Button 按钮类控件 1. PushButton 使⽤ QPushButton 表示⼀个按钮,这也是当前我们最熟悉的⼀个控件了. QPushButton 继承⾃ QAbstractButton . 这个类是⼀个抽象类. 是其他按钮的⽗类. 在…...

RedHat运维-Linux软件包管理基础-RHEL9软件包管理基础
Linux软件包管理基础-RHEL9 1. 对于RHEL9来说,软件包管理基础分为增、删、改、查四个部分。对于增来说,有:增加一个仓库的信息文件、启用一个仓库的信息文件、安装rpm包、解压rpm包、安装软件、安装软件组、更新软件。在这里先讲软件包管理中…...

uniapp----- 判断小程序版本有没有更新
const updateManager uni.getUpdateManager();// 当向小程序后台请求完新版本信息,会进行回调updateManager.onCheckForUpdate(function (res) {console.log(是否有新版本, res.hasUpdate);});// 当新版本下载完成,会进行回调updateManager.onUpdateRea…...

Spring Boot的无缝衔接:深入解析与实践
欢迎来到 破晓的历程的 博客 ⛺️不负时光,不负己✈️ 🚀The begin🚗点点关注,收藏不迷路🚩 引言 在快速迭代的软件开发环境中,无缝衔接是提升开发效率、降低维护成本、增强系统稳定性的关键。Spring Boo…...

在Linux上查找文件的2个好用的命令
在Linux上查找文件,两个非常好用的命令是find和locate。 find命令 find命令非常强大,可以在指定目录下查找符合条件的文件。你可以根据文件名、文件类型、大小、修改日期等多种条件来查找文件。例如,要在当前目录及其子目录下查找所有扩展名…...

实现WebSocket聊天室功能
实现WebSocket聊天室功能 什么是WebSocket?WebSocket的工作原理服务器端实现客户端实现 在现代Web开发中,实时通信已经变得越来越重要。传统的HTTP协议由于其无状态和单向通信的特点,无法很好地满足实时通信的需求。而WebSocket协议则应运而生…...

qt opencv 应用举例
在Qt中使用OpenCV可以实现各种图像处理和计算机视觉任务。以下是一些Qt与OpenCV联合应用的具体举例: 1. 图像读取与显示 读取图像:使用OpenCV的imread函数可以方便地读取各种格式的图像文件,如.bmp、.jpg、.png等。这个函数返回一个Mat对象…...