Skip to content

Commit 225f353

Browse files
Merge branch '5.8.x' into 6.0.x
Closes gh-13413
2 parents e8ab855 + c30baca commit 225f353

File tree

3 files changed

+270
-41
lines changed

3 files changed

+270
-41
lines changed

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

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

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

209387
[[servlet-exceptiontranslationfilter]]
210388
== Handling Security Exceptions
@@ -336,3 +514,52 @@ XML::
336514
=== RequestCacheAwareFilter
337515

338516
The {security-api-url}org/springframework/security/web/savedrequest/RequestCacheAwareFilter.html[`RequestCacheAwareFilter`] uses the <<requestcache,`RequestCache`>> to save the `HttpServletRequest`.
517+
518+
[[servlet-logging]]
519+
== Logging
520+
521+
Spring Security provides comprehensive logging of all security related events at the DEBUG and TRACE level.
522+
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.
523+
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.
524+
525+
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.
526+
With no logs, the user will see a 403 error with no explanation of why the request was rejected.
527+
However, if you enable logging for Spring Security, you will see a log message like this:
528+
529+
[source,text]
530+
----
531+
2023-06-14T09:44:25.797-03:00 DEBUG 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /hello
532+
2023-06-14T09:44:25.797-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/15)
533+
2023-06-14T09:44:25.798-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/15)
534+
2023-06-14T09:44:25.800-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/15)
535+
2023-06-14T09:44:25.801-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/15)
536+
2023-06-14T09:44:25.802-03:00 TRACE 76975 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking CsrfFilter (5/15)
537+
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
538+
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
539+
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]
540+
----
541+
542+
It becomes clear that the CSRF token is missing and that is why the request is being denied.
543+
544+
To configure your application to log all the security events, you can add the following to your application:
545+
546+
====
547+
.application.properties in Spring Boot
548+
[source,properties,role="primary"]
549+
----
550+
logging.level.org.springframework.security=TRACE
551+
----
552+
.logback.xml
553+
[source,xml,role="secondary"]
554+
----
555+
<configuration>
556+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
557+
<!-- ... -->
558+
</appender>
559+
<!-- ... -->
560+
<logger name="org.springframework.security" level="trace" additivity="false">
561+
<appender-ref ref="Console" />
562+
</logger>
563+
</configuration>
564+
----
565+
====

docs/spring-security-docs.gradle

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,17 @@ def generateAttributes() {
4040
def securityReferenceUrl = "$securityDocsUrl/reference/html5/"
4141
def springFrameworkApiUrl = "https://docs.spring.io/spring-framework/docs/$springFrameworkVersion/javadoc-api/"
4242
def springFrameworkReferenceUrl = "https://docs.spring.io/spring-framework/docs/$springFrameworkVersion/reference/html/"
43-
43+
def springBootReferenceUrl = "https://docs.spring.io/spring-boot/docs/$springBootVersion/reference/html/"
44+
4445
return ['gh-old-samples-url': ghOldSamplesUrl.toString(),
4546
'gh-samples-url': ghSamplesUrl.toString(),
4647
'gh-url': ghUrl.toString(),
4748
'security-api-url': securityApiUrl.toString(),
4849
'security-reference-url': securityReferenceUrl.toString(),
4950
'spring-framework-api-url': springFrameworkApiUrl.toString(),
5051
'spring-framework-reference-url': springFrameworkReferenceUrl.toString(),
51-
'spring-security-version': project.version]
52+
'spring-boot-reference-url': springBootReferenceUrl.toString(),
53+
'spring-security-version': project.version]
5254
+ resolvedVersions(project.configurations.testRuntimeClasspath)
5355
}
5456

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=2.4.2
4+
springBootVersion=3.0.8
55
springFrameworkVersion=6.0.10
66
micrometerVersion=1.10.8
77
openSamlVersion=4.1.1

0 commit comments

Comments
 (0)