CSRF Cross-Site Request Forgery – Java Backend Security
Fast recall
Quick revision
Core answer
Authorization. Keep CSRF protection for session cookies, authentication cookies, HTTP Basic credentials, client certificates, and mixed chains that accept any of them. The deciding check is every authentication mechanism accepted by the endpoint, not whether it is called REST or stateless.Interview-ready guide
Interview answer
CSRF protection can be disabled for an endpoint only when that endpoint cannot be authenticated by a credential the browser sends automatically. A common example is a bearer-only API: client code must add the token to the Authorization header, so a cross-site form arrives without an accepted credential.
CSRF must remain enabled when the endpoint accepts a session cookie, a JWT cookie, HTTP Basic authentication, a client certificate, or another ambient credential. Calling an endpoint REST or stateless does not answer the security question. Basic authentication, for example, can be stateless while the browser still resends the credential.
In Spring Security I would apply the decision to a specific SecurityFilterChain after checking all of its authentication mechanisms. A mixed application can keep CSRF for browser pages and use a separate bearer-only chain for /api/**. If a cookie-authenticated request gets a CSRF 403, the correct fix is to submit the expected token rather than disable the protection.
CSRF Cross-Site Request Forgery – Java Backend Security
Direct Answer
Disable Spring Security's CSRF protection only for endpoints that cannot be authenticated by credentials the browser sends automatically. A bearer-only API commonly qualifies because the client must add its token to Authorization. Keep CSRF protection for session cookies, authentication cookies, HTTP Basic credentials, client certificates, and mixed chains that accept any of them. The deciding check is every authentication mechanism accepted by the endpoint, not whether it is called REST or stateless.
Common Mistakes & Pitfalls
- Disabling CSRF for all REST APIs: JSON responses do not determine CSRF risk.
- Checking only for cookies: HTTP Basic and client-certificate credentials may also be sent automatically.
- Assuming stateless means no ambient credentials: stateless Basic authentication is still browser-supplied.
- Removing the filter to silence 403: in a cookie application, make the client submit the token.
- Forgetting mixed security chains: scope the policy to endpoints with the same credential model.
Check your understanding
Answer these without looking back at the article.
- Why is 'disable CSRF for all REST APIs' an incomplete answer?
- If a REST API uses session cookies, should CSRF stay on?
- What single question tells you whether you can safely disable CSRF?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.