Skip to content

Commit 45b81b1

Browse files
author
Steve Riesenberg
committed
Expand migration docs regarding CSRF
Closes gh-12462
1 parent 0d4c619 commit 45b81b1

File tree

1 file changed

+186
-4
lines changed

1 file changed

+186
-4
lines changed

docs/modules/ROOT/pages/migration/servlet/exploits.adoc

Lines changed: 186 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,20 @@ The following steps relate to changes around how to configure CSRF.
77
In Spring Security 5, the default behavior is that the `CsrfToken` will be loaded on every request.
88
This means that in a typical setup, the `HttpSession` must be read for every request even if it is unnecessary.
99

10+
[NOTE]
11+
====
12+
Some examples of where it should be unnecessary to read the session include endpoints marked `permitAll()` such as static assets, static HTML pages, single-page applications hosted under the same domain/server, etc.
13+
====
14+
1015
In Spring Security 6, the default is that the lookup of the `CsrfToken` will be deferred until it is needed.
1116

17+
[NOTE]
18+
====
19+
The `CsrfToken` is needed whenever a request is made with an HTTP verb that would change the state of the application.
20+
This is covered in detail in xref:features/exploits/csrf.adoc#csrf-protection-idempotent[Safe Methods Must be Idempotent].
21+
Additionally, it is needed by any request that renders the token to the response, such as a web page with a `<form>` tag that includes a hidden `<input>` for the CSRF token.
22+
====
23+
1224
To opt into the new Spring Security 6 default, the following configuration can be used.
1325

1426
[[servlet-opt-in-defer-loading-csrf-token]]
@@ -18,7 +30,7 @@ To opt into the new Spring Security 6 default, the following configuration can b
1830
[source,java,role="primary"]
1931
----
2032
@Bean
21-
DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
33+
public SecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
2234
CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
2335
// set the name of the attribute the CsrfToken will be populated on
2436
requestHandler.setCsrfRequestAttributeName("_csrf");
@@ -61,15 +73,164 @@ open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
6173
----
6274
====
6375

64-
If this breaks your application, then you can explicitly opt into the 5.8 defaults using the following configuration:
76+
[NOTE]
77+
====
78+
When the `CsrfToken` is deferred (the default in Spring Security 6), some applications may break due to the fact that they were designed with non-deferred CSRF tokens.
79+
See <<servlet-defer-loading-csrf-token-opt-out,Opt-out Steps>> below for more information.
80+
====
81+
82+
[[servlet-defer-loading-csrf-token-opt-out]]
83+
=== Opt-out Steps
84+
85+
If configuring the `CsrfToken` to be deferred gives you trouble, take a look at these scenarios for optimal opt out behavior:
86+
87+
==== I am using a Single-Page Application with `CookieCsrfTokenRepository`
88+
89+
If you are using a single-page app (SPA) to connect to a backend protected by Spring Security along with `CookieCsrfTokenRepository.withHttpOnlyFalse()`, you may find that the CSRF token is no longer returned to your application as a cookie on the first request to the server.
90+
91+
In this case, you have several options for restoring the behavior your client-side application expects.
92+
One option is to add a `Filter` that eagerly renders the `CsrfToken` to the response regardless of which request is made first, like so:
93+
94+
.Add a `Filter` to return a cookie on the response
95+
====
96+
.Java
97+
[source,java,role="primary"]
98+
----
99+
@Bean
100+
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
101+
CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
102+
CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
103+
// set the name of the attribute the CsrfToken will be populated on
104+
requestHandler.setCsrfRequestAttributeName("_csrf");
105+
http
106+
// ...
107+
.csrf((csrf) -> csrf
108+
.csrfTokenRepository(tokenRepository)
109+
.csrfTokenRequestHandler(requestHandler)
110+
)
111+
.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class);
112+
113+
return http.build();
114+
}
115+
116+
private static final class CsrfCookieFilter extends OncePerRequestFilter {
117+
118+
@Override
119+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
120+
throws ServletException, IOException {
121+
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
122+
// Render the token value to a cookie by causing the deferred token to be loaded
123+
csrfToken.getToken();
124+
125+
filterChain.doFilter(request, response);
126+
}
127+
128+
}
129+
----
130+
131+
.Kotlin
132+
[source,kotlin,role="secondary"]
133+
----
134+
@Bean
135+
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
136+
val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
137+
val requestHandler = CsrfTokenRequestAttributeHandler()
138+
// set the name of the attribute the CsrfToken will be populated on
139+
requestHandler.setCsrfRequestAttributeName("_csrf")
140+
http {
141+
csrf {
142+
csrfTokenRepository = tokenRepository
143+
csrfTokenRequestHandler = requestHandler
144+
}
145+
addFilterAfter<BasicAuthenticationFilter>(CsrfCookieFilter())
146+
}
147+
return http.build()
148+
}
149+
150+
class CsrfCookieFilter : OncePerRequestFilter() {
151+
152+
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
153+
val csrfToken = request.getAttribute(CsrfToken::class.java.name) as CsrfToken
154+
// Render the token value to a cookie by causing the deferred token to be loaded
155+
csrfToken.token
156+
157+
filterChain.doFilter(request, response)
158+
}
159+
160+
}
161+
----
162+
====
163+
164+
The option above does not require changes to the single-page application, but does cause the `CsrfToken` to be loaded on every request.
165+
If you do not wish to add a `Filter` to eagerly load tokens on every request, additional options are listed below.
166+
167+
==== I am using a Single-Page Application with `HttpSessionCsrfTokenRepository`
168+
169+
If you are using sessions, your application will benefit from deferred tokens.
170+
Instead of opting out, another option is to add a new `@RestController` with a `/csrf` endpoint, like so:
171+
172+
.Add a `/csrf` endpoint
173+
====
174+
.Java
175+
[source,java,role="primary"]
176+
----
177+
@RestController
178+
public class CsrfController {
179+
180+
@GetMapping("/csrf")
181+
public CsrfToken csrf(CsrfToken csrfToken) {
182+
return csrfToken;
183+
}
184+
185+
}
186+
----
187+
188+
.Kotlin
189+
[source,kotlin,role="secondary"]
190+
----
191+
@RestController
192+
class CsrfController {
193+
194+
@GetMapping("/csrf")
195+
fun csrf(csrfToken: CsrfToken): CsrfToken {
196+
return csrfToken
197+
}
198+
199+
}
200+
----
201+
====
202+
203+
[NOTE]
204+
====
205+
You may consider adding `.requestMatchers("/csrf").permitAll()` if the endpoint above is required prior to authenticating with the server.
206+
====
207+
208+
The `/csrf` endpoint would need to be consumed by the client-side application in order to bootstrap the application for subsequent requests.
209+
210+
[NOTE]
211+
====
212+
Instructions for calling the `/csrf` endpoint on application launch are specific to your client-side framework and therefore outside the scope of this document.
213+
====
214+
215+
[NOTE]
216+
====
217+
While this requires changes to your single-page application, the benefit is that the CSRF token is only loaded once and the token can continue to be deferred.
218+
This approach works particularly well with applications that use `HttpSessionCsrfTokenRepository` and do benefit from deferred tokens by allowing the `HttpSession` not to be read on every request.
219+
====
220+
221+
If you simply wish to opt out of deferred tokens altogether, that option is listed next.
222+
223+
==== I need to opt out of deferred tokens for another reason
224+
225+
If deferred tokens break your application for another reason, then you can explicitly opt into the 5.8 defaults using the following configuration:
65226

66227
.Explicit Configure `CsrfToken` with 5.8 Defaults
67228
====
68229
.Java
69230
[source,java,role="primary"]
70231
----
71232
@Bean
72-
DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
233+
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
73234
CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
74235
// set the name of the attribute the CsrfToken will be populated on
75236
requestHandler.setCsrfRequestAttributeName(null);
@@ -86,7 +247,7 @@ DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
86247
[source,kotlin,role="secondary"]
87248
----
88249
@Bean
89-
open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
250+
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
90251
val requestHandler = CsrfTokenRequestAttributeHandler()
91252
// set the name of the attribute the CsrfToken will be populated on
92253
requestHandler.setCsrfRequestAttributeName(null)
@@ -115,6 +276,12 @@ open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
115276
----
116277
====
117278

279+
[NOTE]
280+
====
281+
By setting the `csrfRequestAttributeName` to `null`, the `CsrfToken` must first be loaded to determine what attribute name to use.
282+
This causes the `CsrfToken` to be loaded on every request.
283+
====
284+
118285
== Protect against CSRF BREACH
119286

120287
If the steps for <<Defer Loading CsrfToken>> work for you, then you can also opt into Spring Security 6's default support for BREACH protection of the `CsrfToken` using the following configuration:
@@ -240,6 +407,21 @@ open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
240407
----
241408
====
242409

410+
This is the RECOMMENDED way to configure Spring Security to work with a client-side application that uses cookie values, because it continues to allow the response to return a randomized value for the CSRF token in case the application returns HTML or other responses that could be vulnerable to BREACH without your knowledge.
411+
412+
[NOTE]
413+
====
414+
BREACH protection works to protect the token when it is included in a response body that can be GZIP compressed, which generally does not include headers and cookies.
415+
====
416+
417+
[TIP]
418+
====
419+
Any token value returned by the server can be used successfully by the client-side application because the underlying (raw) CSRF token does not change.
420+
It is not required for an AngularJS (or similar) application to refresh the CSRF token before/after every request.
421+
====
422+
423+
If you simply wish to opt out of CSRF BREACH protection altogether, that option is listed next.
424+
243425
==== I need to opt out of CSRF BREACH protection for another reason
244426

245427
If CSRF BREACH protection does not work for you for another reason, you can opt out using the configuration from the <<servlet-opt-in-defer-loading-csrf-token>> section.

0 commit comments

Comments
 (0)