CsrfFilter protects state-changing requests from cross-site request forgery. It permits GET, HEAD, TRACE, and OPTIONS, but requires a valid CSRF token header for POST, PUT, DELETE, and other mutating methods; otherwise it returns HTTP 403 Forbidden. section 9.1
The filter runs in Spring Security’s ordered filter chain. A CsrfTokenRepository generates and manages tokens; the default repository stores a random token in the HTTP session. Requests can retrieve the token from the request’s _csrf attribute. section 9.1 section 5.1
A practical request sequence looks like this:
- Load a page with GET so the application generates or exposes a CSRF token. section 9.1
- Send the token in a request header when calling a mutating endpoint. section 9.1
- Receive the endpoint response only when the token matches the managed value. section 9.1
Testing a protected POST endpoint
A GET request to /hello succeeds and exposes a session-backed token. A POST without the session cookie and X-CSRF-TOKEN header returns 403. Repeating the POST with both values returns the endpoint response. section 9.1
Figure 9.3 The CsrfFilter is one of the filters in the filter chain. It receives the request and eventually forwards it to the next filter in the chain. To manage CSRF tokens, CsrfFilter uses a CsrfTokenRepository.
Shows CsrfFilter’s position in the filter chain and its relationship with CsrfTokenRepository. section 9.1
