CSRF Cross-Site Request Forgery – Java Backend Security
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
A CSRF token is an unpredictable value that the application expects with a state-changing browser request. A server-rendered form can include it as a hidden field. An SPA can read a CSRF cookie and copy the value into a request header. The server compares the submitted value with the token held by its configured repository.
For example, an attacker can submit a hidden form to bank.example/transfer; the victim's browser may attach the bank login cookie automatically. The attacker cannot normally read the bank's CSRF token, so the forged form cannot supply the required value and the server rejects the transfer.
Spring Security enables CSRF protection by default. It supports a session-backed token and CookieCsrfTokenRepository for SPA-style cookie-to-header handling. The important rule is that the server validates a value deliberately submitted by the legitimate client; a token that arrives only as an automatically attached cookie would not provide that check.
CSRF Cross-Site Request Forgery – Java Backend Security
Direct Answer
A CSRF token is an unpredictable value that a legitimate page sends with an unsafe request in a form field or header. The server compares it with the value expected for that user or browser. Another site may cause the browser to send cookies, but it cannot normally read the token from the protected origin, so its forged request lacks a valid token. The token can be stored in a session or another CSRF token repository; it is not required to be a new per-session value for every design.
Common Mistakes & Pitfalls
- Sending a token only as an automatically attached cookie: the server must validate a request field or header as well.
- Assuming every design uses one token per session: token storage and rotation depend on the configured repository.
- Protecting unsafe GET handlers with a token: GET should be read-only; do not use a token to justify side effects.
- Disabling CSRF to remove a 403: first fix how the legitimate client obtains and submits the token.
- Calling it authentication: the login credential identifies the principal; the CSRF check helps establish that an unsafe browser request followed an allowed flow.
Check your understanding
Answer these without looking back at the article.
- Why can't the attacker's site just read the CSRF token and replay it?
- What's the difference between the synchronizer token pattern and double-submit cookie?
- How does Spring Security expose the CSRF token to a JavaScript frontend?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.