SpringSecurity实现原理

实现原理

在Spring Security中认证、授权等功能都是基于过滤器完成的。

在这里插入图片描述

在这里插入图片描述

需要注意的是,默认过滤器并不是直接放在Web项目的原生过滤器链中,而是通过一个FlterChainProxy来统一管理。Spring Security中的过滤器链通过FilterChainProxy嵌入到Web项目的原生过滤器链中。FilterChainProxy 作为一个顶层的管理者,将统一管理SecurityFilter。FilterChainProxy本身是通过Spring框架提供的 DelegatingFilterProxy整合到原生的过滤器链中。

Security Filters

那么在 Spring Security中给我们提供那些过滤器?默认情况下那些过滤器会被加载呢?

以下就是按顺序进行加载的默认过滤器。

在这里插入图片描述

在这里插入图片描述

可以看出,Spring Security提供了30多个过滤器。默认情况下Spring Boot在对Spring Security进入自动化配置时,会创建一个名为SpringSecurityFilerChain的过滤器,并注入到Spring容器中,这个过滤器将负责所有的安全管理,包括用户认证、授权、重定向到登录页面等。具体可以参考WebSecurityConfiguration的源码:

在这里插入图片描述

具体来看这些Filters的加载顺序的话,我们可以进行debug来查看。

(1)首先对springSecurityFilterChain()方法源码进行添加断点

在这里插入图片描述

(2)然后使用debug模式启动项目
在这里插入图片描述

(3)对源码中的securityFilterChain进行计算,就得到默认的过滤器加载顺序了

在这里插入图片描述

SpringBootWebSecurityConfiguration

这个类是spring boot自动配置类,通过这个源码得知,默认情况下对所有请求进行权限控制:

//The default configuration for web security. It relies on Spring Security's content-
//negotiation strategy to determine what sort of authentication to use. If the user 
//specifies their own WebSecurityConfigurerAdapter or SecurityFilterChain bean, this will 
//back-off completely and the users should specify all the bits that they want to configure
//as part of the custom security configuration.
//web安全的默认配置。它依靠Spring Security的内容协商策略来确定使用哪种身份验证。如果用户指定了自己的
//WebSecurityConfigureAdapter或SecurityFilterChain bean,这将完全退出,用户应该指定他们想要配置
//的所有位,作为自定义安全配置的一部分。

@Configuration(proxyBeanMethods = false)
@ConditionalOnDefaultWebSecurity
@ConditionalOnWebApplication(type = Type.SERVLET)
class SpringBootWebSecurityConfiguration {

   @Bean
   @Order(SecurityProperties.BASIC_AUTH_ORDER)
   SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
   															throws Exception {                                         http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
          return http.build();
   }

}

在这里插入图片描述

这就是为什么在引入Spring Security的依赖后没有任何的配置情况下,请求会被拦截的原因。

通过对上面自动配置的分析,我们可以看出默认生效条件是:

在这里插入图片描述

  • 条件一:classpath中存在SecurityFilterChain.class, HttpSecurity.class
  • 条件二:没有自定义 WebSecurityConfigurerAdapter.class, SecurityFilterChain.class

默认情况下,条件都是满足的,WebSecurityConfigurerAdapter这个类极其重要,Spring Security核心配置都在这个类中。

在这里插入图片描述

如果要对Spring Security进行自定义配置,就要自定义这个类实例,通过覆盖类中方法达到修改默认配置的目的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值