深入理解HttpSecurity的设计

news2024/9/28 9:32:16

文章目录

  • HttpSecurity的应用
  • HttpSecurity的类图结构
    • SecurityBuilder接口
    • AbstractConfiguredSecurityBuilder
      • add方法
      • doBuild方法
    • HttpSecurity

HttpSecurity的应用

在上文介绍了基于配置文件的使用方式以及实现细节,如下:

image.png

也就是在配置文件中通过 security:http 等标签来定义了认证需要的相关信息,但是在SpringBoot项目中,我们慢慢脱离了xml配置文件的方式,在SpringSecurity中提供了HttpSecurity等工具类,这里HttpSecurity就等同于在配置文件中定义的http标签。使用方式如下。

image.png

通过代码结果来看和配置文件的效果是一样的。基于配置文件的方式上文已经分析过了,是通过标签对应的handler来解析处理的,那么HttpSecurity这块是如何处理的呢?

HttpSecurity的类图结构

image.png

可以看出HttpSecurity的类图结构相对比较简单,继承了一个父类,实现了两个接口。分别来看看他们的作用是什么。

SecurityBuilder接口

先来看看SecurityBuilder接口,通过字面含义可以发现这是一个帮我们创建对象的工具类。

public interface SecurityBuilder<O> {

	/**
	 * Builds the object and returns it or null.
	 * @return the Object to be built or null if the implementation allows it.
	 * @throws Exception if an error occurred when building the Object
	 */
	O build() throws Exception;

}

通过源码可以看到在SecurityBuilder中给我们提供了一个build()方法。在接口名称处声明了一个泛型,而build()方法返回的正好是这个泛型的对象,其实就很好理解了,也就是SecurityBuilder会创建指定类型的对象。结合HttpSecurity中实现SecurityBuilder接口时指定的泛型可以看出创建的具体对象是什么类型。

image.png

可以看出SecurityBuilder会通过build方法给我们创建一个DefaultSecurityFilterChain对象。也就是拦截请求的那个默认的过滤器链对象。

image.png

进入到doBuild()方法,会进入到AbstractConfiguredSecurityBuilder中的方法

	@Override
	protected final O doBuild() throws Exception {
		synchronized (this.configurers) {
			this.buildState = BuildState.INITIALIZING;
			beforeInit();
			init();
			this.buildState = BuildState.CONFIGURING;
			beforeConfigure();
			configure();
			this.buildState = BuildState.BUILDING;
	 		// 获取构建的对象,上面的方法可以先忽略
			O result = performBuild();
			this.buildState = BuildState.BUILT;
			return result;
		}
	}

进入到HttpSecurity中可以查看performBuild()方法的具体实现。

	@Override
	protected DefaultSecurityFilterChain performBuild() {
        // 对所有的过滤器做排序
		this.filters.sort(OrderComparator.INSTANCE);
		List<Filter> sortedFilters = new ArrayList<>(this.filters.size());
		for (Filter filter : this.filters) {
			sortedFilters.add(((OrderedFilter) filter).filter);
		}
		// 然后生成 DefaultSecurityFilterChain
		return new DefaultSecurityFilterChain(this.requestMatcher, sortedFilters);
	}

在构造方法中绑定了对应的请求匹配器和过滤器集合。

image.png

对应的请求匹配器则是 AnyRequestMatcher 匹配所有的请求。当然我们会比较关心默认的过滤器链中的过滤器是哪来的。

AbstractConfiguredSecurityBuilder

然后再看看AbstractConfiguredSecurityBuilder这个抽象类,他其实是SecurityBuilder的实现,在这儿需要搞清楚他们的关系。

image.png

类型作用
SecurityBuilder声明了build方法
AbstractSecurityBuilder提供了获取对象的方法以及控制一个对象只能build一次
AbstractConfiguredSecurityBuilder除了提供对对象细粒度的控制外还扩展了对configurer的操作

然后对应的三个实现类。

image.png

首先 AbstractConfiguredSecurityBuilder 中定义了一个枚举类,将整个构建过程分为 5 种状态,也可以理解为构建过程生命周期的五个阶段,如下:

private enum BuildState {

		/**
		 * 还没开始构建
		 */
		UNBUILT(0),

		/**
		 * 构建中
		 */
		INITIALIZING(1),

		/**
		 * 配置中
		 */
		CONFIGURING(2),

		/**
		 * 构建中
		 */
		BUILDING(3),

		/**
		 * 构建完成
		 */
		BUILT(4);

		private final int order;

		BuildState(int order) {
			this.order = order;
		}

		public boolean isInitializing() {
			return INITIALIZING.order == this.order;
		}

		/**
		 * Determines if the state is CONFIGURING or later
		 * @return
		 */
		public boolean isConfigured() {
			return this.order >= CONFIGURING.order;
		}

	}

通过这些状态来管理需要构建的对象的不同阶段。

add方法

AbstractConfiguredSecurityBuilder中方法概览

image.png

先来看看add方法。

private <C extends SecurityConfigurer<O, B>> void add(C configurer) {
		Assert.notNull(configurer, "configurer cannot be null");
		Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer
				.getClass();
		synchronized (this.configurers) {
			if (this.buildState.isConfigured()) {
				throw new IllegalStateException("Cannot apply " + configurer + " to already built object");
			}
			List<SecurityConfigurer<O, B>> configs = null;
			if (this.allowConfigurersOfSameType) {
				configs = this.configurers.get(clazz);
			}
			configs = (configs != null) ? configs : new ArrayList<>(1);
			configs.add(configurer);
			this.configurers.put(clazz, configs);
			if (this.buildState.isInitializing()) {
				this.configurersAddedInInitializing.add(configurer);
			}
		}
	}

	/**
	 * Gets all the {@link SecurityConfigurer} instances by its class name or an empty
	 * List if not found. Note that object hierarchies are not considered.
	 * @param clazz the {@link SecurityConfigurer} class to look for
	 * @return a list of {@link SecurityConfigurer}s for further customization
	 */
	@SuppressWarnings("unchecked")
	public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) {
		List<C> configs = (List<C>) this.configurers.get(clazz);
		if (configs == null) {
			return new ArrayList<>();
		}
		return new ArrayList<>(configs);
	}

add 方法,这相当于是在收集所有的配置类。将所有的 xxxConfigure 收集起来存储到 configurers中,将来再统一初始化并配置,configurers 本身是一个 LinkedHashMap ,key 是配置类的 class,value 是一个集合,集合里边放着 xxxConfigure 配置类。当需要对这些配置类进行集中配置的时候,会通过 getConfigurers 方法获取配置类,这个获取过程就是把 LinkedHashMap 中的 value 拿出来,放到一个集合中返回。

doBuild方法

然后看看doBuild方法中的代码

 	@Override
	protected final O doBuild() throws Exception {
		synchronized (this.configurers) {
			this.buildState = BuildState.INITIALIZING;
			beforeInit(); //是一个预留方法,没有任何实现
			init(); // 就是找到所有的 xxxConfigure,挨个调用其 init 方法进行初始化
			this.buildState = BuildState.CONFIGURING;
			beforeConfigure(); // 是一个预留方法,没有任何实现
			configure(); // 就是找到所有的 xxxConfigure,挨个调用其 configure 方法进行配置。
			this.buildState = BuildState.BUILDING;
			O result = performBuild();
// 是真正的过滤器链构建方法,但是在 AbstractConfiguredSecurityBuilder中 performBuild 方法只是一个抽象方法,具体的实现在 HttpSecurity 中
			this.buildState = BuildState.BUILT;
			return result;
		}
	}

init方法:完成所有相关过滤器的初始化

	private void init() throws Exception {
		Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();
		for (SecurityConfigurer<O, B> configurer : configurers) {
			configurer.init((B) this); // 初始化对应的过滤器
		}
		for (SecurityConfigurer<O, B> configurer : this.configurersAddedInInitializing) {
			configurer.init((B) this);
		}
	}

configure方法:完成HttpSecurity和对应的过滤器的绑定。

	private void configure() throws Exception {
		Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();
		for (SecurityConfigurer<O, B> configurer : configurers) {
			configurer.configure((B) this);
		}
	}

HttpSecurity

HttpSecurity 做的事情,就是进行各种各样的 xxxConfigurer 配置

image.png

HttpSecurity 中有大量类似的方法,过滤器链中的过滤器就是这样一个一个配置的。每个配置方法的结尾都会来一句 getOrApply:

	private <C extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>> C getOrApply(C configurer)
			throws Exception {
		C existingConfig = (C) getConfigurer(configurer.getClass());
		if (existingConfig != null) {
			return existingConfig;
		}
		return apply(configurer);
	}

getConfigurer 方法是在它的父类 AbstractConfiguredSecurityBuilder 中定义的,目的就是去查看当前这个 xxxConfigurer 是否已经配置过了。如果当前 xxxConfigurer 已经配置过了,则直接返回,否则调用 apply 方法,这个 apply 方法最终会调用到 AbstractConfiguredSecurityBuilder#add 方法,将当前配置 configurer 收集起来

HttpSecurity 中还有一个 addFilter 方法.

	@Override
	public HttpSecurity addFilter(Filter filter) {
		Integer order = this.filterOrders.getOrder(filter.getClass());
		if (order == null) {
			throw new IllegalArgumentException("The Filter class " + filter.getClass().getName()
					+ " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
		}
		this.filters.add(new OrderedFilter(filter, order));
		return this;
	}

这个 addFilter 方法的作用,主要是在各个 xxxConfigurer 进行配置的时候,会调用到这个方法,(xxxConfigurer 就是用来配置过滤器的),把 Filter 都添加到 fitlers 变量中。

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

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

相关文章

javascript使用正则表达式去除字符串中括号的方法

如下面的例子&#xff1a; (fb6d4f10-79ed-4aff-a915-4ce29dc9c7e1,39996f34-013c-4fc6-b1b3-0c1036c47119,39996f34-013c-4fc6-b1b3-0c1036c47169,39996f34-013c-4fc6-b1b3-0c1036c47111,2430bf64-fd56-460c-8b75-da0a1d1cd74c,39996f34-013c-4fc6-b1b3-0c1036c47112) 上面是前…

华为HCIA(六)

LACPDU中携带接口优先级&#xff0c;系统MAC地址&#xff0c;设备优先级 Mac-vlan命令是配置基于MAC地址的VLAN 二层ACL匹配源目MAC二层协议类型等 HTTP为超文本传输协议&#xff0c;用于网页访问 二层组网指的是AC与AP同在一个网段内 IPV6全球单播地址 华为OSPF内部路由…

Cesium 地球(2)-瓦片创建

Cesium 地球(2)-瓦片创建 QuadtreePrimitive代码执行4个步骤: step1: update()step2: beginFrame()step3: render()step4: endFrame() 但并不是瓦片的创建步骤。 1、创建 QuadtreeTile 基于 step3: render() step3: render()┖ selectTilesForRendering()在 selectTilesFo…

CentOS 7 制作openssl 1.1.1w 版本rpm包 —— 筑梦之路

源码下载地址&#xff1a; https://www.openssl.org/source/openssl-1.1.1w.tar.gz 参考之前的文章&#xff1a; openssl 1.1.1L /1.1.1o/1.1.1t rpm包制作——筑梦之路_openssl的rpm包_筑梦之路的博客-CSDN博客 直接上spec文件&#xff1a; Name: openssl Version: 1.1…

《IP编址与路由:网络层的关键技术》

前言&#xff1a; 在TCP/IP协议栈中&#xff0c;网络层位于第三层&#xff0c;起到了承上启下的关键作用。它不仅负责处理来自数据链路层和传输层的请求&#xff0c;还需确保数据包的正确转发。本文将深入探讨IP编址与路由的相关知识&#xff0c;帮助您更好地理解网络层的重要性…

视觉Transformer在低级视觉领域的研究综述

视觉Transfomer的基本原理 在图像处理过程中&#xff0c;ViT首先将输入的图片分成块&#xff0c;对其进行线性的编码映射后排列成一堆的向量作为编码器的输入&#xff0c;在分类任务中会在这个一维向量加入了一个可学习的嵌入向量用作分类的类别预测结果表示&#xff0c;最后通…

Java:JSR 310日期时间体系LocalDateTime、OffsetDateTime、ZonedDateTime

JSR 310日期时间体系&#xff1a; LocalDateTime&#xff1a;本地日期时间OffsetDateTime&#xff1a;带偏移量的日期时间ZonedDateTime&#xff1a;带时区的日期时间 目录 构造计算格式化参考文章 日期时间包 import java.time.LocalDateTime; import java.time.OffsetDateT…

盲水印接口,版权保护,防止篡改

添加水印&#xff0c;水印生成&#xff0c;获取水印&#xff0c;隐性水印&#xff0c;版权保护&#xff0c;防止篡改&#xff0c;数字媒体分发&#xff0c; 数字取证&#xff0c;水印生成 一、接口介绍 通过上传原始图片和水印图,生成带有隐性水印图的图片。既保持图片的美观…

算法题必备基础技巧(C++版)

最近可能要参加秋招面试........最近还要顺便复习整理一下之前的一些技巧&#xff0c;整理归纳一下。倒不是说放弃考研了&#xff0c;而是尽可能找一个普通的工作保底吧...... 一.函数模板 模板&#xff0c;顾名思义&#xff0c;任何类型都可以套用&#xff0c;分享一个打印任…

【数据分享】2023年全国地级市点位数据(免费获取\shp格式\excel格式)

地级市点位数据是我们各项研究中经常使用到的数据&#xff0c;在之前的文章中我们分享过2022年度的地级市及以上城市的点位数据&#xff08;可查看之前的文章获悉详情&#xff09;。本次我们带来的是2023年度的全国范围的地级市及以上城市的点位数据&#xff0c;点位位置为市政…

【Linux 服务器运维】定时任务 crontab 详解 | 文末送书

文章目录 前言一、crontab 介绍1.1 什么是 crontab1.2 crontab 命令工作流程1.3 Linux 定时任务分类 二、crontab 用法详解2.1 crond 服务安装2.2 crontab 文件内容分析2.3 crontab 命令用法2.3.1 查看定时任务列表2.3.2 编辑/创建定时任务2.3.3 删除定时任务2.3.4 其他 cronta…

NI SCXI-1000 编码器模块

NI SCXI-1000 是 NI&#xff08;National Instruments&#xff09;生产的编码器模块&#xff0c;通常用于工业自动化和控制系统中&#xff0c;以采集和处理编码器信号&#xff0c;用于测量和监测旋转或线性位置。以下是该模块的一些主要产品特点&#xff1a; 编码器输入&#x…

linux内核分析:进程通讯方式

信号 一旦有信号产生,我们就有下面这几种,用户进程对信号的处理方式。 1.执行默认操作。Linux 对每种信号都规定了默认操作,例如,上面列表中的 Term,就是终止进程的意思。Core 的意思是 Core Dump,也即终止进程后,通过 Core Dump 将当前进程的运行状态保存在文件里面…

day1| 704. 二分查找、27. 移除元素

704. 二分查找 题目链接&#xff1a;https://leetcode.cn/problems/binary-search/ 文档讲解&#xff1a;https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html 视频讲解&#xff1a;https://www.bilibili.com/video/BV1fA4y1o715 1、二分法的前提 这道…

SpringSecurity---内存认证和数据库认证

目录 一、内存认证 二、认证逻辑 三、数据库认证&#xff08;也就是用户名和密码在数据库中寻找&#xff09; &#xff08;1&#xff09;mapper层 &#xff08;2&#xff09;启动类添加扫描注解 &#xff08;3&#xff09;编写UserDetailsService实现类 一、内存认证 Co…

GLSL-WebGL着色器语言语法详解

GLSL语法 GLSL它是强类型语言&#xff0c;每一句都必须有分号。它的语法和 typescript 挺像。 GLSL的注释语法和 JS 一样&#xff0c;变量名规则也和 JS 一样&#xff0c;不能使用关键字&#xff0c;保留字&#xff0c;不能以 gl_、webgl_ 或 webgl 开头。运算符基本也和 JS 一…

C++之std::holds_alternative、std::get、std::variant应用实例(二百一十九)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 人生格言&#xff1a; 人生…

AVLoadingIndicatorView - 一个很好的Android加载动画集合

官网 GitHub - HarlonWang/AVLoadingIndicatorView: DEPRECATED 项目简介 AVLoadingIndicatorView is a collection of nice loading animations for Android. You can also find iOS version of this here. Now AVLoadingIndicatorView was updated version to 2.X , If …

git的使用——结合具体问题记录git的使用 代码提交从入门到熟练

前言 git作为开发人员必备的技能&#xff0c;需要熟练掌握&#xff0c;本篇博客记录一些git使用的场景&#xff0c;结合具体问题进行git使用的记录。以gitee的使用为例。 文章目录 前言引出已有项目推送gitee1.gitee中新建项目仓库2.本地项目的初始化提交3.比较好玩的commit图…

【EI会议征稿】2023年工业设计与环境工程国际学术会议

2023 International Conference on Industrial Design and Environmental Engineering 2023年工业设计与环境工程国际学术会议 2023年工业设计与环境工程国际学术会议&#xff08;IDEE 2023&#xff09;将于2023年11月24-26日于郑州召开。本次会议主要围绕工业设计与环境工程…