liveBook · Manning

CsrfFilter

As explained in Spring Security in Action, Second Edition

CsrfFilter is a Spring Security filter that processes protection against cross-site request forgery.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains request methods, token validation, session storage, filter placement, and testing, while deferring custom repository design.
Examples
Uses /hello GET and POST endpoints, curl requests, session cookies, token logging, and a custom filter placed after CsrfFilter.
What it assumes
Assumes basic Spring Security and Java knowledge while introducing filter-chain ordering and token handling through a small application.
What you can do after
Diagnose CSRF failures by retrieving the token, sending the session cookie and header, and interpreting HTTP 403 responses.
How it connects
Connects CSRF protection with HTTP filter chains, CsrfTokenRepository, HTTP sessions, request headers, and HTTP 403 responses.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.