Spring Security-部分官方文档翻译以及思考-SecurityFilterChain

本文介绍了Spring Security基于Servlet过滤器的工作原理,包括DelegatingFilterProxy如何将过滤器与Spring容器连接,FilterChainProxy如何处理过滤器链,以及SecurityFilterChain在确定请求处理过滤器中的作用。内容详细解析了每个组件的功能和相互关系,对于深入理解Spring Security的过滤器机制十分有帮助。
摘要由CSDN通过智能技术生成

回顾一下 Filter 过滤器

Spring Security的Servlet支持基于Servlet过滤器。

下图显示了单个HTTP请求处理程序的典型分层。

FilterChain

客户端向应用程序发送请求,容器创建一个FilterChain,其中包含 Filters 和Servlet,这些 Filters 和 Servlet 应根据请求URI的路径处理 HttpServletRequest。在Spring MVC应用程序中,Servlet 是 DispatcherServlet 的实例。最多一个 Servlet 可以处理单个 HttpServletRequest 和 HttpServletResponse 。但是,可以使用多个过滤器来:

  • 防止调用下游 Filters 或 Servlet。在这种情况下,过滤器通常会写入 HttpServletResponse

  • 修改下游 Filters 和 Servlet 使用的 HttpServletRequest 或 HttpServletResponse

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
   
	// do something before the rest of the application
    chain.doFilter(request, response); // invoke the rest of the application
    // do something after the rest of the application
}

由于 Filters 只影响下游 Filters 和 Servlet ,因此每个 Filter 的调用顺序非常重要。

DelegatingFilterProxy

Spring提供了一个名为 DelegatingFilterProxy的过滤器实现,它允许在 Servlet 容器的生命周期和 Spring 的 ApplicationContext 之间连接。 Servlet 容器允许使用自己的标准注册 Filters ,但它不知道 Spring bean 的定义。 DelegatingFilterProxy可以通过标准的 Servlet 容器注册机制,将所有工作委托给实现过滤器的 Spring Bean 。

下面是 DelegatingFilterProxy如何融入过滤器和过滤链的图片。

DelegatingFilterProxy

DelegatingFilterProxy从 ApplicationContext 中查找 Bean Filter0 ,然后调用 Bean Filter0 。

大白话就是:他的任务就是把持有的 bean 从容器中拿出来。

DelegatingFilterProxy的伪代码如下所示。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
   
	// Lazily get Filter that was registered as a Spring Bean
	// For the example in DelegatingFilterProxy
delegate
 is an instance of Bean Filter0
	Filter delegate = getFilterBean(someBeanName);
	// delegate work to the Spring Bean
	delegate.doFilter(request, response);
}

DelegatingFilterProxy的另一个好处是,它允许延迟查找 Filter bean 实例。这一点很重要,因为容器需要在启动之前注册 Filter 实例。然而, Spring 通常使用 ContextLoaderListener来加载 SpringBean ,直到需要注册 Filter 实例之后才能进行加载。

而注入到 servletContext 的方式是通过 DelegatingFilterProxyRegistrationBean来完成,这个类的主要目的是为了包装 DelegatingFilterProxy类,并且实现自动注入到 servletContext 的流程

DelegatingFilterProxy可以获取到 FilterChainProxy这个bean,而这个 bean 注册 SecurityFilterChain和其中的安全过滤器。

最后使用 SecurityFilterChain来确定当前请求应该调用哪些 Security Filter

所以 DelegatingFilterProxyRegistrationBean就是为了将 SecurityFilterChain加入servlet容器中。

DelegatingFilterProxy就是持有 SecurityFilterChain的 bean 名称的一个 Filter 。

<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值