spring Security源码讲解-WebSecurityConfigurerAdapter

本文主要是介绍spring Security源码讲解-WebSecurityConfigurerAdapter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用security我们最常见的代码:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}@Beanpublic PasswordEncoder getPasswordWncoder(){return new BCryptPasswordEncoder();}
}

这段代码源头是WebSecurityConfiguration这个类下的

	@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();}

首先解释一下这部分代码的作用是返回内置过滤器和用户自己定义的过滤器集合,当然下一节讲解security是怎么使用拿到的过滤器。

setFilterChainProxySecurityConfigurer

webSecurity来自WebSecurityConfiguration中的

	@Autowired(required = false)public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor,@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)throws Exception {webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));if (debugEnabled != null) {webSecurity.debug(debugEnabled);}Collections.sort(webSecurityConfigurers, AnnotationAwareOrderComparator.INSTANCE);Integer previousOrder = null;Object previousConfig = null;for (SecurityConfigurer<Filter, WebSecurity> config : webSecurityConfigurers) {Integer order = AnnotationAwareOrderComparator.lookupOrder(config);if (previousOrder != null && previousOrder.equals(order)) {throw new IllegalStateException("@Order on WebSecurityConfigurers must be unique. Order of "+ order + " was already used on " + previousConfig + ", so it cannot be used on "+ config + " too.");}previousOrder = order;previousConfig = config;}for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {webSecurity.apply(webSecurityConfigurer);}this.webSecurityConfigurers = webSecurityConfigurers;}

setFilterChainProxySecurityConfigurer方法使用的是参数注入的方式,List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)参数会依赖查询SecurityConfigurer实例。
好的我们现在再回头看我们自己定义的SecurityConfig类是继承于WebSecurityConfigurerAdapter ,
在这里插入图片描述
可以看到WebSecurityConfigurerAdapter 实现WebSecurityConfigurer接口

在这里插入图片描述
WebSecurityConfigurer又继承SecurityConfigurer,T此时是WebSecurityConfigurer传递过来的WebSecurity,因此满足SecurityConfigurer<Filter, WebSecurity>,所以也会被setFilterChainProxySecurityConfigurer方法依赖查询到,下面我们debug一下
在这里插入图片描述
有人说这个不能保证就是我们定义类,那好我们给我们自己的类加个标识属性 securityName=“securityName”

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}

在这里插入图片描述
因此就是我们自己定义的类实例被成功依赖查询到作为参数。
好的我们现在接着回到WebSecurityConfiguration类的setFilterChainProxySecurityConfigurer方法

//创建webSecurity实例
webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));
		for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {webSecurity.apply(webSecurityConfigurer);}

将所有SecurityConfigurer实例作为参数调用webSecurity的apply属性

	public <C extends SecurityConfigurer<O, B>> C apply(C configurer) throws Exception {add(configurer);return configurer;}

继续看add方法
在这里插入图片描述

会将SecurityConfigurer添加到webSecurity的configurers属性中。以上过程都是在讲收集SecurityConfigurer并装配到webSecurity的configurers属性。下面继续将我们的源头函数springSecurityFilterChain是怎么使用webSecurity的

springSecurityFilterChain

	public Filter springSecurityFilterChain() throws Exception {boolean hasConfigurers = webSecurityConfigurers != null&& !webSecurityConfigurers.isEmpty();if (!hasConfigurers) {WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {});webSecurity.apply(adapter);}return webSecurity.build();}

主要关心这行代码webSecurity.build()

	public final O build() throws Exception {if (this.building.compareAndSet(false, true)) {this.object = doBuild();return this.object;}throw new AlreadyBuiltException("This object has already been built");}

继续看doBuild()

	@Overrideprotected final O doBuild() throws Exception {synchronized (configurers) {buildState = BuildState.INITIALIZING;beforeInit();init();buildState = BuildState.CONFIGURING;beforeConfigure();configure();buildState = BuildState.BUILDING;O result = performBuild();buildState = BuildState.BUILT;return result;}}

doBuild分别调用了init(),configure(),performBuild()

init()

	@SuppressWarnings("unchecked")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 : configurersAddedInInitializing) {configurer.init((B) this);}}

这里调用了getConfigurers()方法

	private Collection<SecurityConfigurer<O, B>> getConfigurers() {List<SecurityConfigurer<O, B>> result = new ArrayList<SecurityConfigurer<O, B>>();for (List<SecurityConfigurer<O, B>> configs : this.configurers.values()) {result.addAll(configs);}return result;}

this.configurers就是前面SecurityConfigurer存放的位置,这里做的就是将我们的SecurityConfigurer实例存入一个数组中。好到回到我们刚才的位置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 : configurersAddedInInitializing) {configurer.init((B) this);}}

可以清除的看到遍历所有的SecurityConfigurer实例并调用其init(WebSecurity webSecurity)方法。那我们现在看看,我们自己定义的SecurityConfigurer实例init(WebSecurity webSecurity)方法具体的是怎样执行的。
首先找到

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}

alt+鼠标左键点击configure(HttpSecurity http)快速定位
在这里插入图片描述
在getHttp()方法内,接着网上找alt+鼠标左键点击getHttp,
在这里插入图片描述

final HttpSecurity http = getHttp();web.addSecurityFilterChainBuilder(http)

在这里插入图片描述

原来是创建HttpSecurity实例并将对应的HttpSecurity 放入到webSecurity中,因此我们这里可以得出通过调用webSecurity的init()方法,将所有依赖查询到SecurityConfigurer实例的httpSecurity实例存放到webSecurity的securityFilterChainBuilders集合属性中。原来我们定义的

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}@Beanpublic PasswordEncoder getPasswordWncoder(){return new BCryptPasswordEncoder();}
}

这段代码就是这样被用起来的,但是还没结束。继续看webSecurity的configure方法。

configure

在这里插入图片描述
调用的都是SecurityConfigurer实例的configure(webSecurity)方法,这个方法具体做了什么呢?

我们只需要关心SecurityConfigurer的configure方法在这里可以拿到webSecurity。继续看performBuild()

performBuild

注意我们将的init(),configu(),performBuild都是webSecurity的成员方法,因此
在这里插入图片描述
先看一个简单的功能
在这里插入图片描述
debugEnabled控制了日志打印,debugEnabled又是webSecurity属性,我们又能在SecurityConfigurer的configure(webSecurity)方法拿到webSecurity,是不是我们就可以在configure(webSecurity)设置debugEnabled,好的我们尝试一下。

没有设置的效果
在这里插入图片描述
添加修改代码

    @Overridepublic void configure(WebSecurity web) throws Exception {super.configure(web);web.debug(true);}

在这里插入图片描述
在这里插入图片描述
但是这个功能不是我们主要讲的。回到performBuild()方法,我们的重点代码部分
在这里插入图片描述
securityFilterChainBuilders不就是存所有SecurityConfigurer实例的htttpSecurity集合属性。
这里就是遍历所有的httpSecurity属性,调用其的build方法。此时调用的httpSecurity的build,因此我们找到httpSecurity的performBuild()
在这里插入图片描述
requestMatcher和filters是什么?记住这两个属性并带着疑问回到我们常见的代码

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {private String securityName="securityName";@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().permitAll();http.authorizeRequests().antMatchers("/oauth/**", "/login/**","/logout/**").permitAll().anyRequest().authenticated().and().csrf().disable();}
}

在这里插入图片描述
在这里插入图片描述
原来filters就是我们定义的过滤器。接着探索requestMatcher是什么
在这里插入图片描述
我们先看 http.authorizeRequests()方法

在这里插入图片描述
接着看getOrApply()方法

在这里插入图片描述
继续看apply()
在这里插入图片描述
接着看add()
在这里插入图片描述

原来configurer是放入到了HttpSecurity的configurers中,是不是此时有点明白但又有点不明白,总结:我们自己定义的WebSecurityConfigurerAdapter放入到了webSecurity的configurers属性中,而在WebSecurityConfigurerAdapter调用http.formLogin(),http.authorizeRequests()创建的configurer放到各自WebSecurityConfigurerAdapter实例的httpSecurity实例的configurers中。

其实我们查看类也能看到WebSecurityConfigurerAdapter和http.formLogin(),http.authorizeRequests()产生的configurer都继承于SecurityConfigurer,而webSecurity和httpSecurity都继承于和实现相同的类和接口。

所以我们也可以得出httpSecurity调用configure方法其实是调用的http.formLogin(),http.authorizeRequests()产生的configurer实例的configurer(HttpSecurity)方法。

requestMatcher是什么呢
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
回到

在这里插入图片描述查看antMatchers方法
在这里插入图片描述

查看RequestMatchers.antMatchers(antPatterns)的antMatchers方法
在这里插入图片描述
在这里插入图片描述

原来RequestMatchers.antMatchers(antPatterns)方法将我们的路径封装成了RequestMatcher集合,回到
在这里插入图片描述
查看chainRequestMatchers方法
这里我们要回到http.authorizeRequests()
在这里插入图片描述
查看getRegistry方法返回的是ExpressionInterceptUrlRegistry类型
在这里插入图片描述ExpressionInterceptUrlRegistry该类继承于ExpressionUrlAuthorizationConfigurer.AbstractInterceptUrlRegistry
在这里插入图片描述
AbstractInterceptUrlRegistry继承AbstractConfigAttributeRequestMatcherRegistry
在这里插入图片描述
所以这里chainRequestMatchers是AbstractConfigAttributeRequestMatcherRegistry的方法在这里插入图片描述在这里插入图片描述
查看chainRequestMatchersInternal方法,chainRequestMatchersInternal此时是ExpressionUrlAuthorizationConfigurer的成员方法

在这里插入图片描述
因此返回的是 new AuthorizedUrl(requestMatchers);
回到
在这里插入图片描述

继续看AuthorizedUrl的permitAll()方法
在这里插入图片描述
查看access方法
在这里插入图片描述
查看interceptUrl方法
在这里插入图片描述

整个流程
1.创建WebSecurity
2.调用WebSecurity的configure方法,创建HttpSecurity
3.调用WebSecurity的performBuild方法
4.调用HttpSecurity的configure方法,回调consfigure的consfigure(HttpSecurity)方法添加各自的过滤器到HttpSecurity的filters
5.打包HttpSecurity过滤器返回并添加到WebSecurity的securityFilterChains属性
6.封装WebSecurity的securityFilterChains属性为FilterChainProxy
在这里插入图片描述
最终返回包含所有过滤器的 FilterChainProxy实例
在这里插入图片描述
下一节讲FilterChainProxy使用过程

这篇关于spring Security源码讲解-WebSecurityConfigurerAdapter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/574173

相关文章

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui