|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.3.3! |
|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.3.3! |
本节讨论 Spring Security 在基于 Servlet 的应用程序中的高级体系结构。 我们在参考的 Authentication, Authorization, and Protection against Exploits 部分中建立了这种高级理解。
过滤器回顾
Spring Security 的 Servlet 支持基于 Servlet 过滤器,因此通常首先查看过滤器的角色会很有帮助。 下图显示了单个 HTTP 请求的处理程序的典型分层。
客户端向应用程序发送请求,容器创建一个包含实例的 ,并且该容器应根据请求 URI 的路径处理 。
在 Spring MVC 应用程序中,它是 DispatcherServlet 的实例。
最多可以处理单个 和 。
但是,可以使用多个 API 来:FilterChainFilterServletHttpServletRequestServletServletHttpServletRequestHttpServletResponseFilter
-
防止下游实例或 被调用。 在这种情况下,通常会写入 .
FilterServletFilterHttpServletResponse -
修改下游实例使用的 or 和 .
HttpServletRequestHttpServletResponseFilterServlet
力量来自传递给它的东西。FilterFilterChain
FilterChain使用示例-
Java
-
Kotlin
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
}
fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
// 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
}
由于 a 仅影响下游实例和 ,因此调用每个实例的顺序非常重要。FilterFilterServletFilter
委托过滤器代理
Spring 提供了一个名为 DelegatingFilterProxy 的实现,它允许在 Servlet 容器的生命周期和 Spring 的生命周期之间进行桥接。
Servlet 容器允许使用自己的标准注册实例,但它不知道 Spring 定义的 Bean。
您可以通过标准的 Servlet 容器机制进行注册,但将所有工作委托给实现 .FilterApplicationContextFilterDelegatingFilterProxyFilter
下面是如何适应 Filter 实例和 FilterChain 的图片。DelegatingFilterProxy
DelegatingFilterProxy查找Bean 过滤器0从 和 然后调用ApplicationContextBean 过滤器0.
下面的清单显示了 的伪代码:DelegatingFilterProxy
DelegatingFilterProxy伪代码-
Java
-
Kotlin
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
Filter delegate = getFilterBean(someBeanName); (1)
delegate.doFilter(request, response); (2)
}
fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
val delegate: Filter = getFilterBean(someBeanName) (1)
delegate.doFilter(request, response) (2)
}
| 1 | 延迟获取已注册为 Spring Bean 的 Filter。
对于 DelegatingFilterProxy 中的示例,它是delegateBean 过滤器0. |
| 2 | 将工作委托给 Spring Bean。 |
另一个好处是它允许延迟查找 bean 实例。
这一点很重要,因为容器需要先注册实例,然后才能启动容器。
但是, Spring 通常使用 a 来加载 Spring Bean,直到需要注册实例后才会完成。DelegatingFilterProxyFilterFilterContextLoaderListenerFilter
| 1 | 延迟获取已注册为 Spring Bean 的 Filter。
对于 DelegatingFilterProxy 中的示例,它是delegateBean 过滤器0. |
| 2 | 将工作委托给 Spring Bean。 |
FilterChainProxy
Spring Security 的 Servlet 支持包含在 中。 是 Spring Security 提供的特殊功能,它允许通过SecurityFilterChain委托给许多实例。
由于 是一个 Bean,因此它通常包装在 DelegatingFilterProxy 中。FilterChainProxyFilterChainProxyFilterFilterFilterChainProxy
下图显示了 的角色。FilterChainProxy
SecurityFilterChain 安全过滤器链
SecurityFilterChainProxy使用FilterChain来确定应该为当前请求调用哪些 Spring Security 实例。Filter
下图显示了 的角色。SecurityFilterChain
中的安全过滤器通常是 Bean,但它们是用 DelegatingFilterProxy 而不是 DelegatingFilterProxy 注册的。 为直接向 Servlet 容器或 DelegatingFilterProxy 注册提供了许多优势。
首先,它为 Spring Security 的所有 Servlet 支持提供了一个起点。
因此,如果您尝试对 Spring Security 的 Servlet 支持进行故障排除,则添加调试点是一个很好的起点。SecurityFilterChainFilterChainProxyFilterChainProxyFilterChainProxy
其次,由于它是 Spring Security 使用的核心,因此它可以执行不被视为可选的任务。
例如,它会清除 以避免内存泄漏。
它还应用 Spring Security 的 HttpFirewall 来保护应用程序免受某些类型的攻击。FilterChainProxySecurityContext
此外,它还在确定何时应调用 a 方面提供了更大的灵活性。
在 Servlet 容器中,仅根据 URL 调用实例。
但是,可以使用该接口根据 中的任何内容来确定调用。SecurityFilterChainFilterFilterChainProxyHttpServletRequestRequestMatcher
下图显示了多个实例:SecurityFilterChain
在 Multiple SecurityFilterChain 图中,决定应该使用哪个。
仅调用第一个匹配项。
如果请求 URL ,则它首先匹配 的模式,因此仅调用,即使它也匹配 。
如果请求的 URL 为 ,则它与 的模式不匹配,因此请继续尝试每个 。
假设没有其他实例匹配,则调用。FilterChainProxySecurityFilterChainSecurityFilterChain/api/messages/SecurityFilterChain0/api/**SecurityFilterChain0SecurityFilterChainn/messages/SecurityFilterChain0/api/**FilterChainProxySecurityFilterChainSecurityFilterChainSecurityFilterChainn
请注意,它只配置了三个安全实例。
但是,配置了四个安全实例。
请务必注意,每个 Cookie 都可以是唯一的,并且可以单独配置。
事实上,如果应用程序希望 Spring Security 忽略某些请求,则 a 可能没有安全实例。SecurityFilterChain0FilterSecurityFilterChainnFilterSecurityFilterChainSecurityFilterChainFilter
安全过滤器
安全筛选器使用 SecurityFilterChain API 插入到 FilterChainProxy 中。
这些过滤器可用于多种不同的目的,例如身份验证、授权、漏洞利用保护等。
过滤器按特定顺序执行,以确保它们在正确的时间调用,例如,应在执行授权的 之前调用执行身份验证的 。
通常不需要知道 Spring Security 的 Sequences。
但是,有时了解顺序是有益的,如果您想了解它们,您可以查看 FilterOrderRegistration 代码。FilterFilterFilter
为了举例说明上述段落,让我们考虑以下安全配置:
-
Java
-
Kotlin
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(Customizer.withDefaults())
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.formLogin(Customizer.withDefaults());
return http.build();
}
}
import org.springframework.security.config.web.servlet.invoke
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
csrf { }
authorizeHttpRequests {
authorize(anyRequest, authenticated)
}
httpBasic { }
formLogin { }
}
return http.build()
}
}
上述配置将导致以下排序:Filter
| Filter | 添加者 |
|---|---|
|
|
|
|
|
|
|
-
首先,调用 the 来防止 CSRF 攻击。
CsrfFilter -
其次,调用身份验证筛选器来验证请求。
-
第三,调用 the 来授权请求。
AuthorizationFilter
|
可能还有其他未在上面列出的实例。
如果要查看为特定请求调用的过滤器列表,可以打印它们。 |
打印安全过滤器
通常,查看为特定请求调用的安全列表非常有用。
例如,您希望确保已添加的过滤器位于安全过滤器列表中。Filter
筛选器列表在应用程序启动时以 INFO 级别打印,因此您可以在控制台输出上看到类似于以下内容的内容,例如:
2023-06-14T08:55:22.321-03:00 INFO 76975 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [
org.springframework.security.web.session.DisableEncodeUrlFilter@404db674,
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@50f097b5,
org.springframework.security.web.context.SecurityContextHolderFilter@6fc6deb7,
org.springframework.security.web.header.HeaderWriterFilter@6f76c2cc,
org.springframework.security.web.csrf.CsrfFilter@c29fe36,
org.springframework.security.web.authentication.logout.LogoutFilter@ef60710,
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@7c2dfa2,
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@4397a639,
org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@7add838c,
org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5cc9d3d0,
org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7da39774,
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@32b0876c,
org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3662bdff,
org.springframework.security.web.access.ExceptionTranslationFilter@77681ce4,
org.springframework.security.web.access.intercept.AuthorizationFilter@169268a7]
这将很好地了解为每个过滤器链配置的安全过滤器。
但这还不是全部,您还可以将应用程序配置为打印每个请求的每个单独筛选条件的调用。 这有助于查看是否为特定请求调用了已添加的筛选器,或者检查异常的来源。 为此,您可以将应用程序配置为记录安全事件。
将自定义筛选器添加到筛选器链
大多数情况下,默认安全筛选器足以为您的应用程序提供安全性。
但是,有时您可能希望将自定义添加到安全筛选器链中。Filter
例如,假设您要添加一个获取租户 ID 标头的 URL,并检查当前用户是否有权访问该租户。
前面的描述已经给了我们在哪里添加过滤器的线索,因为我们需要知道当前用户,所以我们需要在认证过滤器之后添加它。Filter
首先,让我们创建 :Filter
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
public class TenantFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String tenantId = request.getHeader("X-Tenant-Id"); (1)
boolean hasAccess = isUserAllowed(tenantId); (2)
if (hasAccess) {
filterChain.doFilter(request, response); (3)
return;
}
throw new AccessDeniedException("Access denied"); (4)
}
}
上面的示例代码执行以下操作:
| 1 | 从请求标头中获取租户 ID。 |
| 2 | 检查当前用户是否有权访问租户 ID。 |
| 3 | 如果用户具有访问权限,则调用链中的其余筛选器。 |
| 4 | 如果用户没有访问权限,则抛出 .AccessDeniedException |
|
您可以从 OncePerRequestFilter 扩展,而不是实现 ,OncePerRequestFilter 是过滤器的基类,每个请求仅调用一次,并提供带有 和 参数的方法。 |
现在,我们需要将过滤器添加到安全过滤器链中。
-
Java
-
Kotlin
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.addFilterBefore(new TenantFilter(), AuthorizationFilter.class); (1)
return http.build();
}
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http
// ...
.addFilterBefore(TenantFilter(), AuthorizationFilter::class.java) (1)
return http.build()
}
| 1 | 用于在 .HttpSecurity#addFilterBeforeTenantFilterAuthorizationFilter |
通过在 之前添加过滤器,我们可以确保在身份验证过滤器之后调用 。
你也可以用来在特定Filter之后添加Filter,或者在Filter链中的特定Filter位置添加Filter。AuthorizationFilterTenantFilterHttpSecurity#addFilterAfterHttpSecurity#addFilterAt
就是这样,现在将在过滤器链中调用 ,并检查当前用户是否有权访问租户 ID。TenantFilter
当你将过滤器声明为 Spring bean 时要小心,无论是在配置中对其进行 Comments 还是将其声明为 bean,因为 Spring Boot 会自动将其注册到嵌入式容器中。
这可能会导致过滤器被调用两次,一次由容器调用,一次由 Spring Security 调用,并且顺序不同。@Component
例如,如果您仍然希望将过滤器声明为 Spring bean 以利用依赖关系注入,并避免重复调用,则可以通过声明 bean 并将其属性设置为:FilterRegistrationBeanenabledfalse
@Bean
public FilterRegistrationBean<TenantFilter> tenantFilterRegistration(TenantFilter filter) {
FilterRegistrationBean<TenantFilter> registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
| Filter | 添加者 |
|---|---|
|
|
|
|
|
|
|
|
可能还有其他未在上面列出的实例。
如果要查看为特定请求调用的过滤器列表,可以打印它们。 |
| 1 | 从请求标头中获取租户 ID。 |
| 2 | 检查当前用户是否有权访问租户 ID。 |
| 3 | 如果用户具有访问权限,则调用链中的其余筛选器。 |
| 4 | 如果用户没有访问权限,则抛出 .AccessDeniedException |
|
您可以从 OncePerRequestFilter 扩展,而不是实现 ,OncePerRequestFilter 是过滤器的基类,每个请求仅调用一次,并提供带有 和 参数的方法。 |
| 1 | 用于在 .HttpSecurity#addFilterBeforeTenantFilterAuthorizationFilter |
处理安全异常
ExceptionTranslationFilter 允许将 AccessDeniedException 和 AuthenticationException 转换为 HTTP 响应。
ExceptionTranslationFilter作为安全筛选器之一插入到 FilterChainProxy 中。
下图显示了 与其他组件的关系:ExceptionTranslationFilter
-
首先,调用 以调用应用程序的其余部分。ExceptionTranslationFilterFilterChain.doFilter(request, response) -
如果用户未经过身份验证或用户是 ,则开始身份验证。AuthenticationException-
保存 ,以便在身份验证成功后可用于重播原始请求。
HttpServletRequest -
用于从客户端请求凭据。 例如,它可能会重定向到登录页面或发送标头。
AuthenticationEntryPointWWW-Authenticate
-
否则,如果它是 ,则为 Access Denied。
调用 以处理被拒绝的访问。AccessDeniedExceptionAccessDeniedHandler
|
如果应用程序不抛出 an 或 an ,则不执行任何操作。 |
的伪代码如下所示:ExceptionTranslationFilter
try {
filterChain.doFilter(request, response); (1)
} catch (AccessDeniedException | AuthenticationException ex) {
if (!authenticated || ex instanceof AuthenticationException) {
startAuthentication(); (2)
} else {
accessDenied(); (3)
}
}
| 1 | 如 筛选器回顾 中所述,调用等效于调用应用程序的其余部分。
这意味着,如果应用程序的另一部分(FilterSecurityInterceptor或方法安全性)抛出OR,则会在此处捕获并处理它。FilterChain.doFilter(request, response)AuthenticationExceptionAccessDeniedException |
| 2 | 如果用户未经过身份验证,或者用户是 Start Authentication。AuthenticationException |
| 3 | 否则,Access Denied (访问被拒绝) |
|
如果应用程序不抛出 an 或 an ,则不执行任何操作。 |
| 1 | 如 筛选器回顾 中所述,调用等效于调用应用程序的其余部分。
这意味着,如果应用程序的另一部分(FilterSecurityInterceptor或方法安全性)抛出OR,则会在此处捕获并处理它。FilterChain.doFilter(request, response)AuthenticationExceptionAccessDeniedException |
| 2 | 如果用户未经过身份验证,或者用户是 Start Authentication。AuthenticationException |
| 3 | 否则,Access Denied (访问被拒绝) |
在身份验证之间保存请求
如处理安全异常中所述,当请求没有身份验证并且针对需要身份验证的资源时,需要保存请求,以便经过身份验证的资源在身份验证成功后重新请求。
在 Spring Security 中,这是通过使用 RequestCache 实现保存来完成的。HttpServletRequest
请求缓存
保存在 RequestCache 中。
当用户成功进行身份验证时,将使用 重播原始请求。
RequestCacheAwareFilter 在用户进行身份验证后使用 to get saved,而 在 将用户重定向到登录端点之前,使用 to save after it detect 。HttpServletRequestRequestCacheRequestCacheHttpServletRequestExceptionTranslationFilterRequestCacheHttpServletRequestAuthenticationException
默认情况下,使用 an。
下面的代码演示了如何自定义用于检查 for a saved 请求的 for a saved 请求(如果存在 named 的参数)。HttpSessionRequestCacheRequestCacheHttpSessioncontinue
RequestCache如果参数存在,则仅检查保存的请求continue-
Java
-
Kotlin
-
XML
@Bean
DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setMatchingRequestParameterName("continue");
http
// ...
.requestCache((cache) -> cache
.requestCache(requestCache)
);
return http.build();
}
@Bean
open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
val httpRequestCache = HttpSessionRequestCache()
httpRequestCache.setMatchingRequestParameterName("continue")
http {
requestCache {
requestCache = httpRequestCache
}
}
return http.build()
}
<http auto-config="true">
<!-- ... -->
<request-cache ref="requestCache"/>
</http>
<b:bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache"
p:matchingRequestParameterName="continue"/>
阻止保存请求
出于多种原因,您可能希望不在会话中存储用户的未经身份验证的请求。 您可能希望将该存储卸载到用户的浏览器上或将其存储在数据库中。 或者您可能希望关闭此功能,因为您总是希望将用户重定向到主页,而不是他们在登录前尝试访问的页面。
为此,您可以使用 NullRequestCache 实现。
-
Java
-
Kotlin
-
XML
@Bean
SecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
RequestCache nullRequestCache = new NullRequestCache();
http
// ...
.requestCache((cache) -> cache
.requestCache(nullRequestCache)
);
return http.build();
}
@Bean
open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
val nullRequestCache = NullRequestCache()
http {
requestCache {
requestCache = nullRequestCache
}
}
return http.build()
}
<http auto-config="true">
<!-- ... -->
<request-cache ref="nullRequestCache"/>
</http>
<b:bean id="nullRequestCache" class="org.springframework.security.web.savedrequest.NullRequestCache"/>
RequestCacheAwareFilter
RequestCacheAwareFilter使用RequestCache重播原始请求。
Logging
Spring Security 在 DEBUG 和 TRACE 级别提供了所有与安全相关的事件的全面日志记录。 这在调试应用程序时非常有用,因为为了安全措施, Spring Security 不会在响应正文中添加请求被拒绝原因的任何详细信息。 如果您遇到 401 或 403 错误,您很可能会找到一条日志消息,帮助您了解发生了什么。
让我们考虑一个例子,用户尝试向启用了 CSRF 保护的资源发出请求,但没有 CSRF 令牌。
如果没有日志,用户将看到 403 错误,并且没有解释请求被拒绝的原因。
但是,如果为 Spring Security 启用日志记录,则会看到如下日志消息:POST
2023-06-14T09:44:25.797-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /hello
2023-06-14T09:44:25.797-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15)
2023-06-14T09:44:25.798-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15)
2023-06-14T09:44:25.800-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/15)
2023-06-14T09:44:25.801-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15)
2023-06-14T09:44:25.802-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15)
2023-06-14T09:44:25.814-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:8080/hello
2023-06-14T09:44:25.814-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code
2023-06-14T09:44:25.814-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match request to [Is Secure]
很明显,CSRF 令牌丢失了,这就是请求被拒绝的原因。
要将应用程序配置为记录所有安全事件,可以将以下内容添加到应用程序中:
logging.level.org.springframework.security=TRACE
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- ... -->
</appender>
<!-- ... -->
<logger name="org.springframework.security" level="trace" additivity="false">
<appender-ref ref="Console" />
</logger>
</configuration>