Skip to content

Commit 2e4b417

Browse files
Merge branch '6.0.x'
Closes gh-13414
2 parents f91a51b + 225f353 commit 2e4b417

File tree

2 files changed

+266
-39
lines changed

2 files changed

+266
-39
lines changed

docs/modules/ROOT/pages/servlet/architecture.adoc

Lines changed: 265 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -164,44 +164,222 @@ In fact, a `SecurityFilterChain` might have zero security `Filter` instances if
164164
== Security Filters
165165

166166
The Security Filters are inserted into the <<servlet-filterchainproxy>> with the <<servlet-securityfilterchain>> API.
167-
The <<servlet-filters-review,order of `Filter`>> instances matters.
168-
It is typically not necessary to know the ordering of Spring Security's `Filter` instances.
169-
However, there are times that it is beneficial to know the ordering.
170-
171-
The following is a comprehensive list of Spring Security Filter ordering:
172-
173-
* xref:servlet/authentication/session-management.adoc#session-mgmt-force-session-creation[`ForceEagerSessionCreationFilter`]
174-
* `ChannelProcessingFilter`
175-
* `WebAsyncManagerIntegrationFilter`
176-
* `SecurityContextPersistenceFilter`
177-
* `HeaderWriterFilter`
178-
* `CorsFilter`
179-
* `CsrfFilter`
180-
* `LogoutFilter`
181-
* `OAuth2AuthorizationRequestRedirectFilter`
182-
* `Saml2WebSsoAuthenticationRequestFilter`
183-
* `X509AuthenticationFilter`
184-
* `AbstractPreAuthenticatedProcessingFilter`
185-
* `CasAuthenticationFilter`
186-
* `OAuth2LoginAuthenticationFilter`
187-
* `Saml2WebSsoAuthenticationFilter`
188-
* xref:servlet/authentication/passwords/form.adoc#servlet-authentication-usernamepasswordauthenticationfilter[`UsernamePasswordAuthenticationFilter`]
189-
* `DefaultLoginPageGeneratingFilter`
190-
* `DefaultLogoutPageGeneratingFilter`
191-
* `ConcurrentSessionFilter`
192-
* xref:servlet/authentication/passwords/digest.adoc#servlet-authentication-digest[`DigestAuthenticationFilter`]
193-
* `BearerTokenAuthenticationFilter`
194-
* xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[`BasicAuthenticationFilter`]
195-
* <<requestcacheawarefilter,RequestCacheAwareFilter>>
196-
* `SecurityContextHolderAwareRequestFilter`
197-
* `JaasApiIntegrationFilter`
198-
* `RememberMeAuthenticationFilter`
199-
* `AnonymousAuthenticationFilter`
200-
* `OAuth2AuthorizationCodeGrantFilter`
201-
* `SessionManagementFilter`
202-
* <<servlet-exceptiontranslationfilter,`ExceptionTranslationFilter`>>
203-
* xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`]
204-
* `SwitchUserFilter`
167+
Those filters can be used for a number of different purposes, like xref:servlet/authentication/index.adoc[authentication], xref:servlet/authorization/index.adoc[authorization], xref:servlet/exploits/index.adoc[exploit protection], and more.
168+
The filters are executed in a specific order to guarantee that they are invoked at the right time, for example, the `Filter` that performs authentication should be invoked before the `Filter` that performs authorization.
169+
It is typically not necessary to know the ordering of Spring Security's ``Filter``s.
170+
However, there are times that it is beneficial to know the ordering, if you want to know them, you can check the {gh-url}/config/src/main/java/org/springframework/security/config/annotation/web/builders/FilterOrderRegistration.java[`FilterOrderRegistration` code].
171+
172+
To exemplify the above paragraph, let's consider the following security configuration:
173+
174+
====
175+
.Java
176+
[source,java,role="primary"]
177+
----
178+
@Configuration
179+
@EnableWebSecurity
180+
public class SecurityConfig {
181+
182+
@Bean
183+
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
184+
http
185+
.csrf(Customizer.withDefaults())
186+
.authorizeHttpRequests(authorize -> authorize
187+
.anyRequest().authenticated()
188+
)
189+
.httpBasic(Customizer.withDefaults())
190+
.formLogin(Customizer.withDefaults());
191+
return http.build();
192+
}
193+
194+
}
195+
----
196+
.Kotlin
197+
[source,kotlin,role="secondary"]
198+
----
199+
import org.springframework.security.config.web.servlet.invoke
200+
201+
@Configuration
202+
@EnableWebSecurity
203+
class SecurityConfig {
204+
205+
@Bean
206+
fun filterChain(http: HttpSecurity): SecurityFilterChain {
207+
http {
208+
csrf { }
209+
authorizeHttpRequests {
210+
authorize(anyRequest, authenticated)
211+
}
212+
httpBasic { }
213+
formLogin { }
214+
}
215+
return http.build()
216+
}
217+
218+
}
219+
----
220+
====
221+
222+
The above configuration will result in the following `Filter` ordering:
223+
224+
[cols="1,1", options="header"]
225+
|====
226+
| Filter | Added by
227+
| xref:servlet/exploits/csrf.adoc[CsrfFilter] | `HttpSecurity#csrf`
228+
| xref:servlet/authentication/passwords/form.adoc#servlet-authentication-form[UsernamePasswordAuthenticationFilter] | `HttpSecurity#formLogin`
229+
| xref:servlet/authentication/passwords/basic.adoc[BasicAuthenticationFilter] | `HttpSecurity#httpBasic`
230+
| xref:servlet/authorization/authorize-http-requests.adoc[AuthorizationFilter] | `HttpSecurity#authorizeHttpRequests`
231+
|====
232+
233+
1. First, the `CsrfFilter` is invoked to protect against xref:servlet/exploits/csrf.adoc[CSRF attacks].
234+
2. Second, the authentication filters are invoked to authenticate the request.
235+
3. Third, the `AuthorizationFilter` is invoked to authorize the request.
236+
237+
[NOTE]
238+
====
239+
There might be other `Filter` instances that are not listed above.
240+
If you want to see the list of filters invoked for a particular request, you can <<servlet-print-filters,print them>>.
241+
====
242+
243+
[[servlet-print-filters]]
244+
=== Printing the Security Filters
245+
246+
Often times, it is useful to see the list of security ``Filter``s that are invoked for a particular request.
247+
For example, you want to make sure that the <<adding-custom-filter,filter you have added>> is in the list of the security filters.
248+
249+
The list of filters is printed at INFO level on the application startup, so you can see something like the following on the console output for example:
250+
251+
[source,text,role="terminal"]
252+
----
253+
2023-06-14T08:55:22.321-03:00 INFO 76975 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [
254+
org.springframework.security.web.session.DisableEncodeUrlFilter@404db674,
255+
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@50f097b5,
256+
org.springframework.security.web.context.SecurityContextHolderFilter@6fc6deb7,
257+
org.springframework.security.web.header.HeaderWriterFilter@6f76c2cc,
258+
org.springframework.security.web.csrf.CsrfFilter@c29fe36,
259+
org.springframework.security.web.authentication.logout.LogoutFilter@ef60710,
260+
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@7c2dfa2,
261+
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@4397a639,
262+
org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@7add838c,
263+
org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5cc9d3d0,
264+
org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7da39774,
265+
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@32b0876c,
266+
org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3662bdff,
267+
org.springframework.security.web.access.ExceptionTranslationFilter@77681ce4,
268+
org.springframework.security.web.access.intercept.AuthorizationFilter@169268a7]
269+
----
270+
271+
And that will give a pretty good idea of the security filters that are configured for <<servlet-securityfilterchain,each filter chain>>.
272+
273+
But that is not all, you can also configure your application to print the invocation of each individual filter for each request.
274+
That is helpful to see if the filter you have added is invoked for a particular request or to check where an exception is coming from.
275+
To do that, you can configure your application to <<servlet-logging,log the security events>>.
276+
277+
[[adding-custom-filter]]
278+
=== Adding a Custom Filter to the Filter Chain
279+
280+
Mostly of the times, the default security filters are enough to provide security to your application.
281+
However, there might be times that you want to add a custom `Filter` to the security filter chain.
282+
283+
For example, let's say that you want to add a `Filter` that gets a tenant id header and check if the current user has access to that tenant.
284+
The previous description already gives us a clue on where to add the filter, since we need to know the current user, we need to add it after the authentication filters.
285+
286+
First, let's create the `Filter`:
287+
288+
[source,java]
289+
----
290+
import java.io.IOException;
291+
292+
import jakarta.servlet.Filter;
293+
import jakarta.servlet.FilterChain;
294+
import jakarta.servlet.ServletException;
295+
import jakarta.servlet.ServletRequest;
296+
import jakarta.servlet.ServletResponse;
297+
import jakarta.servlet.http.HttpServletRequest;
298+
import jakarta.servlet.http.HttpServletResponse;
299+
300+
import org.springframework.security.access.AccessDeniedException;
301+
302+
public class TenantFilter implements Filter {
303+
304+
@Override
305+
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
306+
HttpServletRequest request = (HttpServletRequest) servletRequest;
307+
HttpServletResponse response = (HttpServletResponse) servletResponse;
308+
309+
String tenantId = request.getHeader("X-Tenant-Id"); <1>
310+
boolean hasAccess = isUserAllowed(tenantId); <2>
311+
if (hasAccess) {
312+
filterChain.doFilter(request, response); <3>
313+
return;
314+
}
315+
throw new AccessDeniedException("Access denied"); <4>
316+
}
317+
318+
}
319+
320+
----
321+
322+
The sample code above does the following:
323+
324+
<1> Get the tenant id from the request header.
325+
<2> Check if the current user has access to the tenant id.
326+
<3> If the user has access, then invoke the rest of the filters in the chain.
327+
<4> If the user does not have access, then throw an `AccessDeniedException`.
328+
329+
[TIP]
330+
====
331+
Instead of implementing `Filter`, you can extend from {spring-framework-api-url}org/springframework/web/filter/OncePerRequestFilter.html[OncePerRequestFilter] which is a base class for filters that are only invoked once per request and provides a `doFilterInternal` method with the `HttpServletRequest` and `HttpServletResponse` parameters.
332+
====
333+
334+
Now, we need to add the filter to the security filter chain.
335+
336+
====
337+
.Java
338+
[source,java,role="primary"]
339+
----
340+
@Bean
341+
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
342+
http
343+
// ...
344+
.addFilterBefore(new TenantFilter(), AuthorizationFilter.class); <1>
345+
return http.build();
346+
}
347+
----
348+
.Kotlin
349+
[source,kotlin,role="secondary"]
350+
----
351+
@Bean
352+
fun filterChain(http: HttpSecurity): SecurityFilterChain {
353+
http
354+
// ...
355+
.addFilterBefore(TenantFilter(), AuthorizationFilter::class.java) <1>
356+
return http.build()
357+
}
358+
----
359+
====
360+
361+
<1> Use `HttpSecurity#addFilterBefore` to add the `TenantFilter` before the `AuthorizationFilter`.
362+
363+
By adding the filter before the `AuthorizationFilter` we are making sure that the `TenantFilter` is invoked after the authentication filters.
364+
You can also use `HttpSecurity#addFilterAfter` to add the filter after a particular filter or `HttpSecurity#addFilterAt` to add the filter at a particular filter position in the filter chain.
365+
366+
And that's it, now the `TenantFilter` will be invoked in the filter chain and will check if the current user has access to the tenant id.
367+
368+
Be careful when you declare your filter as a Spring bean, either by annotating it with `@Component` or by declaring it as a bean in your configuration, because Spring Boot will automatically {spring-boot-reference-url}web.html#web.servlet.embedded-container.servlets-filters-listeners.beans[register it with the embedded container].
369+
That may cause the filter to be invoked twice, once by the container and once by Spring Security and in a different order.
370+
371+
If you still want to declare your filter as a Spring bean to take advantage of dependency injection for example, and avoid the duplicate invocation, you can tell Spring Boot to not register it with the container by declaring a `FilterRegistrationBean` bean and setting its `enabled` property to `false`:
372+
373+
[source,java]
374+
----
375+
@Bean
376+
public FilterRegistrationBean<TenantFilter> tenantFilterRegistration(TenantFilter filter) {
377+
FilterRegistrationBean<TenantFilter> registration = new FilterRegistrationBean<>(filter);
378+
registration.setEnabled(false);
379+
return registration;
380+
}
381+
----
382+
205383

206384
[[servlet-exceptiontranslationfilter]]
207385
== Handling Security Exceptions
@@ -333,3 +511,52 @@ XML::
333511
=== RequestCacheAwareFilter
334512

335513
The {security-api-url}org/springframework/security/web/savedrequest/RequestCacheAwareFilter.html[`RequestCacheAwareFilter`] uses the <<requestcache,`RequestCache`>> to save the `HttpServletRequest`.
514+
515+
[[servlet-logging]]
516+
== Logging
517+
518+
Spring Security provides comprehensive logging of all security related events at the DEBUG and TRACE level.
519+
This can be very useful when debugging your application because for security measures Spring Security does not add any detail of why a request has been rejected to the response body.
520+
If you come across a 401 or 403 error, it is very likely that you will find a log message that will help you understand what is going on.
521+
522+
Let's consider an example where a user tries to make a `POST` request to a resource that has xref:servlet/exploits/csrf.adoc[CSRF protection] enabled without the CSRF token.
523+
With no logs, the user will see a 403 error with no explanation of why the request was rejected.
524+
However, if you enable logging for Spring Security, you will see a log message like this:
525+
526+
[source,text]
527+
----
528+
2023-06-14T09:44:25.797-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /hello
529+
2023-06-14T09:44:25.797-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15)
530+
2023-06-14T09:44:25.798-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15)
531+
2023-06-14T09:44:25.800-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/15)
532+
2023-06-14T09:44:25.801-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15)
533+
2023-06-14T09:44:25.802-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15)
534+
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
535+
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
536+
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]
537+
----
538+
539+
It becomes clear that the CSRF token is missing and that is why the request is being denied.
540+
541+
To configure your application to log all the security events, you can add the following to your application:
542+
543+
====
544+
.application.properties in Spring Boot
545+
[source,properties,role="primary"]
546+
----
547+
logging.level.org.springframework.security=TRACE
548+
----
549+
.logback.xml
550+
[source,xml,role="secondary"]
551+
----
552+
<configuration>
553+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
554+
<!-- ... -->
555+
</appender>
556+
<!-- ... -->
557+
<logger name="org.springframework.security" level="trace" additivity="false">
558+
<appender-ref ref="Console" />
559+
</logger>
560+
</configuration>
561+
----
562+
====

gradle.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
aspectjVersion=1.9.19
22
reactorVersion=2022.0.8
33
springJavaformatVersion=0.0.39
4-
springBootVersion=3.0.6
4+
springBootVersion=3.1.1
55
springFrameworkVersion=6.0.10
66
micrometerVersion=1.10.8
77
openSamlVersion=4.1.1

0 commit comments

Comments
 (0)