118 Star 906 Fork 400

doocs / source-code-hunter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
SpringSecurity请求全过程解析.md 9.55 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2021-08-21 10:53 . docs: update readme guideline

Spring Security 请求全过程解析

Spring Security 是一款基于 Spring 的安全框架,主要包含认证和授权两大安全模块,和另外一款流行的安全框架 Apache Shiro 相比,它拥有更为强大的功能。Spring Security 也可以轻松的自定义扩展以满足各种需求,并且对常见的 Web 安全攻击提供了防护支持。如果你的 Web 框架选择的是 Spring,那么在安全方面 Spring Security 会是一个不错的选择。

这里我们使用 Spring Boot 来集成 Spring Security,Spring Boot 版本为**2.5.3,Spring Security 版本为5.5.1**。

开启 Spring Security

使用 IDEA 创建一个 Spring Boot 项目,然后引入**spring-boot-starter-security**:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

接下来我们创建一个**HelloController**,对外提供一个/hello服务:

@RestController
public class HelloController {
    @GetMapping("hello")
    public String hello() {
        return "hello world";
    }
}

这时候我们直接启动项目,访问http://localhost:8080/hello,可以看到页面跳转到一个登陆页面:

image-20210811091508157

默认的用户名为 user,密码由 Sping Security 自动生成,回到 IDEA 的控制台,可以找到密码信息:

Using generated security password: 4f06ba04-37e9-4bdd-a085-3305260da0d6

输入用户名 user,密码 4f06ba04-37e9-4bdd-a085-3305260da0d6 后,我们便可以成功访问/hello接口。

基本原理

Spring Security 默认为我们开启了一个简单的安全配置,下面让我们来了解其原理。

当 Spring Boot 项目配置了 Spring Security 后,Spring Security 的整个加载过程如下图所示:

image-20210811091633434

而当我们访问http://localhost:8080/hello时,代码的整个执行过程如下图所示:

image-20210811091659121

如上图所示,Spring Security 包含了众多的过滤器,这些过滤器形成了一条链,所有请求都必须通过这些过滤器后才能成功访问到资源。

下面我们通过 debug 来验证这个过程:

首先,通过前面可以知道,当有请求来到时,最先由**DelegatingFilterProxy负责接收,因此在DelegatingFilterProxy**的doFilter()的首行打上断点:

image-20210811091719470

接着**DelegatingFilterProxy会将请求委派给FilterChainProxy进行处理,在FilterChainProxy**的首行打上断点:

img

**FilterChainProxy会在doFilterInternal()中生成一个内部类VirtualFilterChain的实例,以此来调用 Spring Security 的整条过滤器链,在VirtualFilterChain**的doFilter()首行打上断点:

image-20210811091755498

接下来**VirtualFilterChain会通过currentPosition依次调用存在additionalFilters中的过滤器,其中比较重要的几个过滤器有:UsernamePasswordAuthenticationFilterDefaultLoginPageGeneratingFilterAnonymousAuthenticationFilterExceptionTranslationFilterFilterSecurityInterceptor**,我们依次在这些过滤器的doFilter()的首行打上断点:

image-20210811091815473

准备完毕后,我们启动项目,然后访问http://localhost:8080/hello,程序首先跳转到**DelegatingFilterProxy**的断点上:

image-20210811091833065

此时**delegate还是 null 的,接下来依次执行代码,可以看到delegate最终被赋值一个FilterChainProxy**的实例:

img

接下来程序依次跳转到**FilterChainProxydoFilter()VirtualFilterChain**的doFilter()中:

img

image-20210811092048784

接着程序跳转到**AbstractAuthenticationProcessingFilterUsernamePasswordAuthenticationFilter**的父类)的doFilter()中,通过requiresAuthentication()判定为 false(是否是 POST 请求):

img

接着程序跳转到**DefaultLoginPageGeneratingFilter**的doFilter()中,通过isLoginUrlRequest()判定为 false(请求路径是否是/login):

img

接着程序跳转到**AnonymousAuthenticationFilterdoFilter()中,由于是首次请求,此时SecurityContextHolder.getContext().getAuthentication()为 null,因此会生成一个AnonymousAuthenticationToken**的实例:

img

接着程序跳转到**ExceptionTranslationFilterdoFilter()中,ExceptionTranslationFilter负责处理FilterSecurityInterceptor**抛出的异常,我们在 catch 代码块的首行打上断点:

img

接着程序跳转到**FilterSecurityInterceptordoFilter()中,依次执行代码后程序停留在其父类(AbstractSecurityInterceptor**)的attemptAuthorization()中:

img

accessDecisionManagerAccessDecisionManager(访问决策器)的实例,AccessDecisionManager主要有 3 个实现类:AffirmativeBased(一票通过),ConsensusBased(少数服从多数)、UnanimousBased(一票否决),此时**AccessDecisionManager的的实现类是AffirmativeBased,我们可以看到程序进入AffirmativeBased**的decide()中:

img

从上图可以看出,决策的关键在voter.vote(authentication, object, configAttributes)这句代码上,通过跟踪调试,程序最终进入**AuthenticationTrustResolverImpl**的isAnonymous()中:

img

isAssignableFrom()判断前者是否是后者的父类,而**anonymousClass被固定为AnonymousAuthenticationToken.class,参数authentication由前面AnonymousAuthenticationFilter可以知道是AnonymousAuthenticationToken的实例,因此isAnonymous()返回 true,FilterSecurityInterceptor抛出AccessDeniedException异常,程序返回ExceptionTranslationFilter**的 catch 块中:

img

接着程序会依次进入**DelegatingAuthenticationEntryPointLoginUrlAuthenticationEntryPoint中,最后由LoginUrlAuthenticationEntryPoint**的commence()决定重定向到/login

img

后续对/login的请求同样会经过之前的执行流程,在**DefaultLoginPageGeneratingFilterdoFilter()中,通过isLoginUrlRequest()判定为 true(请求路径是否是/login),直接返回login.html**,也就是我们开头看到的登录页面。

当我们输入用户名和密码,点击**Sign in,程序来到AbstractAuthenticationProcessingFilterdoFilter()中,通过requiresAuthentication()判定为 true(是否是 POST 请求),因此交给其子类UsernamePasswordAuthenticationFilter进行处理,UsernamePasswordAuthenticationFilter会将用户名和密码封装成一个UsernamePasswordAuthenticationToken**的实例并进行校验,当校验通过后会将请求重定向到我们一开始请求的路径:/hello

后续对/hello的请求经过过滤器链时就可以一路开绿灯直到最终交由**HelloController**返回"Hello World"。

参考

  1. Spring Security Reference

  2. Spring Boot 中开启 Spring Security

Java
1
https://gitee.com/Doocs/source-code-hunter.git
git@gitee.com:Doocs/source-code-hunter.git
Doocs
source-code-hunter
source-code-hunter
main

搜索帮助