CSRF Cross-Site Request Forgery – Java Backend Security
Fast recall
Quick revision
Core answer
SameSite cookies, origin checks, and keeping GET, HEAD, OPTIONS, and TRACE free of state changes.Interview-ready guide
Interview answer
CSRF is an attack in which another site causes a browser to send an unwanted request to an application where the user already has credentials. A bank-transfer form is the usual example: the malicious page submits the form, the browser adds the bank's session cookie, and the bank may see an authenticated request even though the user did not intend it.
The important condition is not JWT versus session; it is whether the browser supplies a credential automatically. Session cookies are the common case, but HTTP Basic credentials and client certificates can also be ambient. A bearer token added explicitly to the Authorization header is different because a normal cross-site form cannot add that header or read the token.
For a cookie-authenticated Spring application, CSRF protection should remain enabled. Spring requires an unpredictable token on unsafe requests and rejects a missing or invalid token. SameSite cookies and origin checks provide additional protection. Safe methods such as GET must remain read-only, because links and embedded resources can trigger them easily.
CSRF Cross-Site Request Forgery – Java Backend Security
Direct Answer
Cross-Site Request Forgery (CSRF) tricks a browser into sending an unwanted request with credentials that the browser adds automatically. A session cookie is the usual example, but HTTP Basic credentials and client certificates can also be sent automatically. The server sees valid credentials unless it checks that the request came through an allowed flow. Common defenses are a CSRF token on unsafe requests, SameSite cookies, origin checks, and keeping GET, HEAD, OPTIONS, and TRACE free of state changes.
Common Mistakes & Pitfalls
- Confusing CSRF with XSS: XSS runs attacker-controlled script in a trusted page; CSRF sends a forged request with ambient credentials.
- Calling it a cookie-only attack: cookies are the usual cause, but HTTP Basic authentication and client certificates may also be sent automatically.
- Changing state with GET: links and embedded resources can trigger GET requests. Safe HTTP methods must not perform mutations.
- Disabling protection because an endpoint is called REST: the name of the API does not matter; credential transport does.
- Believing HTTPS stops CSRF: TLS protects the connection, not the intent of an authenticated request.
Check your understanding
Answer these without looking back at the article.
- Why does CSRF work because of how browsers handle cookies?
- How does a synchronizer (anti-CSRF) token stop the attack?
- Why are stateless JWT APIs that use the Authorization header largely immune to CSRF?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.