Cross-site request forgery (CSRF) tricks a user who is already authenticated into opening a page whose scripts perform unwanted state-changing actions in the trusted application. A foreign page can therefore impersonate the user through the user's existing login. section 9.1
Spring Security enables CSRF protection by default. It generates a CSRF token when a page loads, and clients must include that token in requests that change application state, such as HTTP POST requests. section 9.0 section 9.1
The Spring Security implementation connects the protection mechanism to the filter chain:
- CsrfFilter receives requests and uses a CsrfTokenRepository to manage CSRF tokens. section 9.1
- The filter places the token on the request under the _csrf attribute, making it available to application code. section 9.1
- A request without the expected token is rejected with HTTP 403, while a request carrying the session cookie and X-CSRF-TOKEN succeeds. section 9.1
- Customization is organized around CsrfToken, CsrfTokenRepository, and CsrfTokenRequestHandler. section 9.4
Testing a protected REST endpoint
A small REST application exposes GET and POST endpoints at /hello. Calling GET first establishes the session and exposes a token. Calling POST without the token returns 403; repeating POST with the JSESSIONID cookie and X-CSRF-TOKEN header returns the endpoint response. section 9.1
Figure 9.1 After the user logs into their account, they access a page containing forgery code. This code impersonates the user and can execute unwanted actions on behalf of the user.
Visualizes how forgery code on a page accessed after authentication can execute unwanted actions for the user. section 9.1
Figure 9.2 To make a POST request, the client needs to add a header containing the CSRF token. The application generates a CSRF token when the page is loaded (via a GET request), and the token is added to all requests that can be made from the loaded page. This way, only the loaded page can make mutating requests.
Shows the page-load token flow and the required header for mutating requests. section 9.1




