SpringSecurity源码分析-过滤器链是如何植入到spring中的

SpringSecurity源码分析-过滤器链是如何植入到spring中的

一切的源头都是因为在web.xml中配置了这样一个Filter

<!--security--><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>

DelegatingFilterProxy中加载FilterChainProxy

  1. 这是一个模板类,是一个过滤器链代理对象,SpringSecurity中的FilterChainProxy通过这个过滤器植入进来
  2. DelegatingFilterProxy是对外提供的,用于植入外部过滤器链的类
  3. FilterChainProxy在这个类中被植入Spring中.
public class DelegatingFilterProxy extends GenericFilterBean {@Nullableprivate String contextAttribute;@Nullableprivate WebApplicationContext webApplicationContext;@Nullableprivate String targetBeanName;private boolean targetFilterLifecycle;@Nullable/** 真实的过滤器 */private volatile Filter delegate;private final Object delegateMonitor;public DelegatingFilterProxy() {this.targetFilterLifecycle = false;this.delegateMonitor = new Object();}public DelegatingFilterProxy(Filter delegate) {this.targetFilterLifecycle = false;this.delegateMonitor = new Object();Assert.notNull(delegate, "Delegate Filter must not be null");this.delegate = delegate;}public DelegatingFilterProxy(String targetBeanName) {this(targetBeanName, (WebApplicationContext)null);}public DelegatingFilterProxy(String targetBeanName, @Nullable WebApplicationContext wac) {this.targetFilterLifecycle = false;this.delegateMonitor = new Object();Assert.hasText(targetBeanName, "Target Filter bean name must not be null or empty");this.setTargetBeanName(targetBeanName);this.webApplicationContext = wac;if (wac != null) {this.setEnvironment(wac.getEnvironment());}}public void setContextAttribute(@Nullable String contextAttribute) {this.contextAttribute = contextAttribute;}@Nullablepublic String getContextAttribute() {return this.contextAttribute;}public void setTargetBeanName(@Nullable String targetBeanName) {this.targetBeanName = targetBeanName;}@Nullableprotected String getTargetBeanName() {return this.targetBeanName;}public void setTargetFilterLifecycle(boolean targetFilterLifecycle) {this.targetFilterLifecycle = targetFilterLifecycle;}protected boolean isTargetFilterLifecycle() {return this.targetFilterLifecycle;}/** 这个方法在父类的init方法中调用,这个方法构造真实的过滤器*/protected void initFilterBean() throws ServletException {synchronized(this.delegateMonitor) {if (this.delegate == null) {if (this.targetBeanName == null) {this.targetBeanName = this.getFilterName();}WebApplicationContext wac = this.findWebApplicationContext();if (wac != null) {this.delegate = this.initDelegate(wac);}}}}public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {Filter delegateToUse = this.delegate;if (delegateToUse == null) {synchronized(this.delegateMonitor) {delegateToUse = this.delegate;if (delegateToUse == null) {WebApplicationContext wac = this.findWebApplicationContext();if (wac == null) {throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener or DispatcherServlet registered?");}delegateToUse = this.initDelegate(wac);}this.delegate = delegateToUse;}}/** 调用真实过滤器中的doFilter方法*/this.invokeDelegate(delegateToUse, request, response, filterChain);}public void destroy() {Filter delegateToUse = this.delegate;if (delegateToUse != null) {this.destroyDelegate(delegateToUse);}}@Nullableprotected WebApplicationContext findWebApplicationContext() {if (this.webApplicationContext != null) {if (this.webApplicationContext instanceof ConfigurableApplicationContext) {ConfigurableApplicationContext cac = (ConfigurableApplicationContext)this.webApplicationContext;if (!cac.isActive()) {cac.refresh();}}return this.webApplicationContext;} else {String attrName = this.getContextAttribute();return attrName != null ? WebApplicationContextUtils.getWebApplicationContext(this.getServletContext(), attrName) : WebApplicationContextUtils.findWebApplicationContext(this.getServletContext());}}/** 获取过滤器链 springSecurityFilterChain*/protected Filter initDelegate(WebApplicationContext wac) throws ServletException {String targetBeanName = this.getTargetBeanName();Assert.state(targetBeanName != null, "No target bean name set");/** 根据名字和类型获取获取过滤器链,这里的targetBeanName即springSecurityFilterChain,这个是在Spring中写死的,自动装配的..*/Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class);if (this.isTargetFilterLifecycle()) {delegate.init(this.getFilterConfig());}return delegate;}protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {delegate.doFilter(request, response, filterChain);}protected void destroyDelegate(Filter delegate) {if (this.isTargetFilterLifecycle()) {delegate.destroy();}}
}

小结:通过过滤器链代理对象DelegatingFilterProxy找到真正的过滤器链FilterChainProxy,然后去一个一个的过滤器去处理请求

FilterChainProxy

  1. private List filterChains 存储过滤器链
  2. doFilter方法中调用doFilterInternal方法
  3. 获取到所有的过滤器,挨个执行filter的filter方法
public class FilterChainProxy extends GenericFilterBean {// ~ Static fields/initializers// =====================================================================================private static final Log logger = LogFactory.getLog(FilterChainProxy.class);// ~ Instance fields// ================================================================================================private final static String FILTER_APPLIED = FilterChainProxy.class.getName().concat(".APPLIED");/**存储过滤器链**/private List<SecurityFilterChain> filterChains;private FilterChainValidator filterChainValidator = new NullFilterChainValidator();private HttpFirewall firewall = new StrictHttpFirewall();// ~ Methods// ========================================================================================================public FilterChainProxy() {}public FilterChainProxy(SecurityFilterChain chain) {this(Arrays.asList(chain));}public FilterChainProxy(List<SecurityFilterChain> filterChains) {this.filterChains = filterChains;}@Overridepublic void afterPropertiesSet() {filterChainValidator.validate(this);}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;if (clearContext) {try {request.setAttribute(FILTER_APPLIED, Boolean.TRUE);doFilterInternal(request, response, chain);}finally {SecurityContextHolder.clearContext();request.removeAttribute(FILTER_APPLIED);}}else {doFilterInternal(request, response, chain);}}private void doFilterInternal(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {FirewalledRequest fwRequest = firewall.getFirewalledRequest((HttpServletRequest) request);HttpServletResponse fwResponse = firewall.getFirewalledResponse((HttpServletResponse) response);/** 获取过滤器 */List<Filter> filters = getFilters(fwRequest);if (filters == null || filters.size() == 0) {if (logger.isDebugEnabled()) {logger.debug(UrlUtils.buildRequestUrl(fwRequest)+ (filters == null ? " has no matching filters": " has an empty filter list"));}fwRequest.reset();/** 挨个执行过滤器*/chain.doFilter(fwRequest, fwResponse);return;}VirtualFilterChain vfc = new VirtualFilterChain(fwRequest, chain, filters);vfc.doFilter(fwRequest, fwResponse);}/*** Returns the first filter chain matching the supplied URL.** @param request the request to match* @return an ordered array of Filters defining the filter chain*/private List<Filter> getFilters(HttpServletRequest request) {for (SecurityFilterChain chain : filterChains) {if (chain.matches(request)) {return chain.getFilters();}}return null;}/*** Convenience method, mainly for testing.** @param url the URL* @return matching filter list*/public List<Filter> getFilters(String url) {return getFilters(firewall.getFirewalledRequest((new FilterInvocation(url, "GET").getRequest())));}/*** @return the list of {@code SecurityFilterChain}s which will be matched against and* applied to incoming requests.*/public List<SecurityFilterChain> getFilterChains() {return Collections.unmodifiableList(filterChains);}/*** Used (internally) to specify a validation strategy for the filters in each* configured chain.** @param filterChainValidator the validator instance which will be invoked on during* initialization to check the {@code FilterChainProxy} instance.*/public void setFilterChainValidator(FilterChainValidator filterChainValidator) {this.filterChainValidator = filterChainValidator;}/*** Sets the "firewall" implementation which will be used to validate and wrap (or* potentially reject) the incoming requests. The default implementation should be* satisfactory for most requirements.** @param firewall*/public void setFirewall(HttpFirewall firewall) {this.firewall = firewall;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append("FilterChainProxy[");sb.append("Filter Chains: ");sb.append(filterChains);sb.append("]");return sb.toString();}// ~ Inner Classes// ==================================================================================================/*** Internal {@code FilterChain} implementation that is used to pass a request through* the additional internal list of filters which match the request.*/private static class VirtualFilterChain implements FilterChain {private final FilterChain originalChain;private final List<Filter> additionalFilters;private final FirewalledRequest firewalledRequest;private final int size;private int currentPosition = 0;private VirtualFilterChain(FirewalledRequest firewalledRequest,FilterChain chain, List<Filter> additionalFilters) {this.originalChain = chain;this.additionalFilters = additionalFilters;this.size = additionalFilters.size();this.firewalledRequest = firewalledRequest;}@Overridepublic void doFilter(ServletRequest request, ServletResponse response)throws IOException, ServletException {if (currentPosition == size) {if (logger.isDebugEnabled()) {logger.debug(UrlUtils.buildRequestUrl(firewalledRequest)+ " reached end of additional filter chain; proceeding with original chain");}// Deactivate path stripping as we exit the security filter chainthis.firewalledRequest.reset();originalChain.doFilter(request, response);}else {currentPosition++;Filter nextFilter = additionalFilters.get(currentPosition - 1);if (logger.isDebugEnabled()) {logger.debug(UrlUtils.buildRequestUrl(firewalledRequest)+ " at position " + currentPosition + " of " + size+ " in additional filter chain; firing Filter: '"+ nextFilter.getClass().getSimpleName() + "'");}nextFilter.doFilter(request, response, this);}}}public interface FilterChainValidator {void validate(FilterChainProxy filterChainProxy);}private static class NullFilterChainValidator implements FilterChainValidator {@Overridepublic void validate(FilterChainProxy filterChainProxy) {}}}

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

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

相关文章

NoSQL 之 Redis 集群部署

前言&#xff1a; &#xff08;1&#xff09;主从复制&#xff1a;主从复制是高可用Redis的基础&#xff0c;哨兵和集群都是在主从复制基础上实现高可用 的。主从复制主要实现了数据的多机备份&#xff0c;以及对于读操作的负载均衡和简单的故障恢复。缺陷&#xff1a; 故障…

vue3+antd 实现文件夹目录右键菜单功能

原本的目录结构&#xff1a; 右键菜单&#xff1a; 点击菜单以后会触发回调&#xff1a; 完整的前端代码&#xff1a; <template><a-directory-treev-model:expandedKeys"expandedKeys"v-model:selectedKeys"selectedKeys"multipleshow-li…

在 Docker 容器中运行 Vite 开发环境,有这两个问题要注意

容器化开发给我们带来了很多便捷&#xff0c;但是在开发环境下也有一些问题要注意&#xff0c;如果不解决这些问题&#xff0c;你的开发体验不会很好。 容器启动正常&#xff0c;却无法访问 我们用 Docker 启动一个 Vite Vue3 项目的开发环境后&#xff0c;发现端口日志一切…

计算机如何存储浮点数

浮点数组成 在计算机中浮点数通常由三部分组成&#xff1a;符号位、指数位、尾数位。IEEE-754中32位浮点数如下&#xff1a; 上图32bit浮点数包含1bit的符号位&#xff0c;8比特的指数位和23bit的尾数位。对于一个常规浮点数&#xff0c;我们来看看它是如何存储和计算的。这里…

conda env pip install error:No space left on device

conda 环境 pip install error&#xff1a;No space left on device 文章目录 conda 环境 pip install error&#xff1a;No space left on device现象1 实验2 分析和解决办法 现象 非root用户的服务器&#xff0c;需要安装环境&#xff0c;安装的环境超过2GB sudo pip insta…

医疗机器人中的具身智能进展——自主超声策略模型的任务编码和局部探索

医疗机器人一直是具身智能的研究热点。医学图像、医疗触诊、血压血氧、心率脉搏和生物电信号等多模态生物医学信息&#xff0c;不断丰富着医疗机器人的感知范畴。 自主超声 “自主超声”属于具身智能医疗机器人领域中话题度较高的研究方向。作为临床检查的重要手段之一&#…

线性系统理论及应用GUI设计及仿真

目录 1.控制系统的状态空间模型 1.1.状态空间模型 1.2 传递函数模型 1.3 传递函数转换为状态空间模型 1.4.状态空间模型转换为传递函数 1.5.状态空间模型转化为约当标准型 2.线性系统的时域分析 2.1.矩阵指数函数的计算 2.2.线型定常连续系统的状态空间模型求解 3.线…

ubuntu24.04按关键字卸载不需要的apt包

使用的时候发现一个imagemagic无法正常读取文件&#xff0c;试图卸载 man apt经过尝试后&#xff0c;发现list的一个神奇关键字&#xff0c;用来显示已安装的软件包 sudo apt list --installed | grep image按image关键字过滤&#xff1a; 之后按软件名卸载即可 sudo apt pu…

开关电源——调制模式和工作模式

一、开关电源的调制模式 开关电源作为一种广泛应用于电子设备中&#xff0c;用于将一定电压和电流转换为另一种电压和电流的技术&#xff0c;以下是开关电源三种常见的调制模式&#xff1a; 脉冲宽度调制&#xff08;Pulse Width Modulation&#xff09; 脉冲频率调制&#xff…

高德地图 key 和安全密钥使用

参考高德地图&#xff1a;JS API 安全密钥使用 高德地图 key 和安全密钥使用 一、通过明文方式设置参数查看如下成功后返回的信息 二、通过代理服务器转发实验&#xff1a;通过本地地址转发返回错的错误信息&#xff0c;如下通过正确的项目的的服务地址&#xff0c;返回正常参数…

【VUE基础】VUE3第一节—vite创建vue3工程

什么是VUE Vue (发音为 /vjuː/&#xff0c;类似 view) 是一款用于构建用户界面的 JavaScript 框架。它基于标准 HTML、CSS 和 JavaScript 构建&#xff0c;并提供了一套声明式的、组件化的编程模型&#xff0c;帮助你高效地开发用户界面。无论是简单还是复杂的界面&#xff0…

Java+MySQL8.0.36+ElementUI数字化产科信息管理系统之”五色管理”

JavaMySQL8.0.36ElementUI数字化产科信息管理系统之”五色管理” 一、数字化产科信息管理系统概述 数字化产科信息管理五色管理是一种基于孕产妇妊娠风险的分类管理方法&#xff0c;通过数字化手段实现孕产妇全周期的健康风险评估与管理。该方法将孕产妇按照风险等级分为绿色、…

DC-DC充放电原理

文章目录 前言1. 电子器件1.1 电容1.2 电感 2. 升压电路3. 降压电路4. 电压均衡电路4.1 被动均衡4.2 主动均衡 5. 我的疑问5.1 对于升压电路&#xff0c;怎么设计升压到多少V后&#xff0c;停止升压&#xff1f;5.2 什么是等效电阻&#xff1f;5.3 快充是如何实现的&#xff1f…

LightGlue: Local Feature Matching at Light Speed【文献阅读】

论文&#xff1a;LightGlue: Local Feature Matching at Light Speed 代码&#xff1a;https://github.com/cvg/LightGlue 作者&#xff1a;1 ETH Zurich__2 Microsoft Mixed Reality & AI Lab Abstract 提出的LightGlue是一个深度神经网络用于学习图像间的局部特征匹配。…

WAIC | 上海人形机器人创新中心 | 最新演讲 | 详细整理

前言 笔者看了7月4号的人形机器人与具身智能发展论坛的直播&#xff0c;并在7月5日到了上海WAIC展会现场参观。这次大会的举办很有意义&#xff0c;听并看了各家的最新成果&#xff0c;拍了很多照片视频&#xff0c;部分演讲也录屏了在重复观看学习 稍后会相继整理创立穹彻智…

算法系列--分治排序|归并排序|逆序对的求解

一.基本概念与实现 归并排序(mergeSort)也是基于分治思想的一种排序方式,思路如下: 分解:根据中间下标mid将数组分解为两部分解决:不断执行上述分解过程,当分解到只有一个元素时,停止分解,此时就是有序的合并:合并两个有序的子区间,所有子区间合并的结果就是原问题的解 归并…

第一节 网络安全概述

一.网络空间安全 网络空间&#xff1a;一个由信息基础设施组成相互依赖的网络。 ---- 海陆空天&#xff08;大海、陆 地、天空、航天&#xff09; 通信保密阶段 ---- 计算机安全 ----- 信息系统安全 ----- 网络空间安全 计算机安全&#xff1a;开始秉持着“严于律己&#x…

C语言 指针和数组—指针数组及其在字符串处理中的应用

目录 问题的提出 问题的解决 回头看——指针、数组及其他类型的混合 指针数组与指向数组的指针 字符串的排序 问题的提出 问题的解决 回头看——指针、数组及其他类型的混合  基本数据类型  int 、 long 、 char 、 short 、 float 、 double……  数组是一种从…

设计模式之模版方法

模版方法介绍 模版方法&#xff08;Template Method&#xff09;模式是一种行为型设计模式&#xff0c;它定义了一个操作&#xff08;模板方法&#xff09;的基本组合与控制流程&#xff0c;将一些步骤&#xff08;抽象方法&#xff09;推迟到子类中&#xff0c;使得子类可以在…

【UE5.1】Chaos物理系统基础——03 炸开几何体集

目录 步骤 一、通过径向向量将几何体集炸开 二、优化炸开效果——让破裂的碎块自然下落 三、优化炸开效果——让碎块旋转起来 四、优化炸开效果——让碎块旋转的越来越慢 步骤 一、通过径向向量将几何体集炸开 1. 打开上一篇中&#xff08;【UE5.1】Chaos物理系统基础—…