CSRF protection prevents a forged page from using an authenticated user's browser to perform unwanted state-changing actions. Spring Security enables it by default, so an HTTP POST without a valid CSRF token is rejected with HTTP 403. section 9.0 section 9.1
The protection mechanism issues a token when a page loads, then requires clients to send that token with mutating requests. CsrfFilter validates the request through a CsrfTokenRepository before allowing the filter chain to continue. section 9.1
Apply the mechanism in this sequence:
- Keep CSRF protection enabled for browser-based web applications whose pages and state-changing endpoints are served by the same application. section 9.2
- Include the token in every mutating request; HTML forms can submit it as a hidden input using `${_csrf.parameterName}` and `${_csrf.token}`. section 9.2
- Use the default protection for non-GET, non-HEAD, non-TRACE, and non-OPTIONS requests unless a specific application requirement justifies customization. section 9.3
- Exclude selected paths with `ignoringRequestMatchers`, or replace token storage and request handling through the CSRF configuration. section 9.3 section 9.4
Protected POST endpoint
A `/hello` POST endpoint returns HTTP 403 when called without a token. After a GET obtains the token, a request carrying the session cookie and `X-CSRF-TOKEN` succeeds. A Thymeleaf form achieves the same result with a hidden CSRF input.
Custom token persistence
A custom CsrfTokenRepository can generate a UUID, associate it with an `X-IDENTIFIER` header, and store it through JPA in a database. Later POST requests must send the matching identifier and token.
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.
Visualizes how a page obtains a CSRF token and attaches it to mutating requests. section 9.1
