CsrfTokenRepository is the Spring Security contract that manages CSRF tokens for CsrfFilter: it generates, stores, retrieves, and eventually invalidates token values. The default implementation stores random strings in the HTTP session, which is sufficient for many applications. section 9.1 section 9.4
A custom implementation supplies the repository operations that Spring Security calls:
- generateToken(HttpServletRequest) creates a token, such as a UUID wrapped in DefaultCsrfToken with the X-CSRF-TOKEN header and _csrf request attribute. section 9.3
- saveToken(CsrfToken, HttpServletRequest, HttpServletResponse) persists or updates the token for the request’s identifier. section 9.3
- loadToken(HttpServletRequest) retrieves the stored token and returns null when no token exists. section 9.3
- HttpSecurity wires the implementation through csrfTokenRepository(customTokenRepository). section 9.3
Replacing session storage can support applications that serve many requests and require horizontal scaling. A database-backed repository uses an identifier, such as X-IDENTIFIER, to associate each caller with its current token; mutating requests must send the matching X-CSRF-TOKEN value. section 9.3 section 9.1
Database-backed repository
Define a Token JPA entity with identifier and token fields, expose a JpaTokenRepository lookup by identifier, and implement CustomCsrfTokenRepository. Configure it with http.csrf(c -> c.csrfTokenRepository(customTokenRepository)). A GET request for /hello with X-IDENTIFIER:12345 generates and stores a token; a POST using that identifier and the matching X-CSRF-TOKEN succeeds, while a POST without the token returns HTTP 403 Forbidden. section 9.3 section 9.1
Figure 9.10 The CsrfToken uses a custom implementation of CsrfTokenRepository. This custom implementation uses a JpaRepository to manage CSRF tokens in a database.
Shows the custom repository using JpaRepository to manage CSRF tokens in a database. section 9.3
