zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Spring Security 里的filer们

2023-02-25 18:27:16 时间

这段文字主要源于对 https://docs.spring.io/spring-security/reference/servlet/architecture.html 的学习和理解,其实就是对下图的理解。

1)使用 Spring Security

要使用Spring Security,如果是在Spring Boot环境,那么只需要导入security的starter,Spring Boot就会自动做下面的事。 Creates a servlet Filter as a bean named springSecurityFilterChain. This bean is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application. Registers the Filter with a bean named springSecurityFilterChain with the Servlet container for every request. Creates a UserDetailsService bean with a username of user and a randomly generated password that is logged to the console.

不使用Spring Boot的情况下,就需要自己在web.xml文件中定义springSecurityFilterChain。


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

2)入口 DelegatingFilterProxy

下面通过源码简单看下DelegatingFilterProxy实例化的过程。 Tomcat启动时会在 web 容器中初始化 DelegatingFilterProxy 实例。

DelegatingFilterProxy 本身既是一个Filter也是一个ServletContextAware的实例。Spring 使用 ContextLoaderListener 来加载spring的bean。org.springframework.web.context.support.GenericWebApplicationContext 则是servlet context和spring context真正交汇的地方。 从下面DelegatingFilterProxy实现的接口就可以感知到 DelegatingFilterProxy 最关键的作用就是作为Servlet Container 和 Spring Context的桥梁。 因为Spring要等web context初始化完成才能初始化自己的context,所以如果在spring中定义的filter beans就可以延迟初始化。通过延迟初始化就解决了Filter必须定义在Servlet Container中的问题。Spring很巧妙的通过FilterChain接口把这些filter beans串在一起。

public class DelegatingFilterProxy extends GenericFilterBean

而 ServletContextAware 是Spring的一个接口。

public abstract class GenericFilterBean implements Filter, BeanNameAware, EnvironmentAware,
    EnvironmentCapable, ServletContextAware, InitializingBean, DisposableBean

从DelegatingFilterProxy的两个关键fields:WebApplicationContext webApplicationContext 和 Filter delegate,也能知道DelegatingFilterProxy桥梁作用。

上图中的delegate是FilterChainProxy的实例。

3) FilterChainProxy 包装了 filers

下图中filterChian包含的filters是不做任何特殊配置时的16个filters。FilerChainProxy就是通过调用它拥有的filters起到了对request做filter处理的作用,这就是称它为代理的原因.

4)DelegatingFilterProxy得到springSecurityFilterChain

上面提到 DelegatingFilterProxy 对filter延迟初始化的作用。所以对delegate的赋值只发生处理第一个http request时。被命名为springSecurityFilterChain的FilterChainProxy会从spring context中被找出来并设置到DelegatingFilterProxy的delegate field。

至此,应该对文首的第一个图能说出点儿什么了吧… …


Reference: [1]: https://www.baeldung.com/spring-web-contexts [2]: https://docs.spring.io/spring-security/reference/servlet/architecture.html