Spring Security defends against Cross-Site Request Forgery by requiring a unique, unpredictable CSRF token on every state-changing request, so a forged request from another site cannot be replayed without knowing that token.
Key Points: • A CsrfToken is generated per session (or per request) and must be echoed back in a hidden form field or header. • Spring Security rejects POST/PUT/DELETE requests missing a valid matching token. • CSRF protection is enabled by default for browser-based, session-authenticated apps in Spring Security. • It is commonly disabled for stateless REST APIs authenticated via JWT/OAuth2, since there is no session cookie for an attacker to ride on. • Disabling CSRF should be paired with strict CORS rules and token-based auth to avoid reopening the risk.
Example: A stateless microservice that only accepts requests carrying a bearer token in the Authorization header has no session cookie to forge, so the team disables CSRF via http.csrf(csrf -> csrf.disable()) while keeping CORS locked down.
Interview Tip: A concise interview answer is:
"Spring Security prevents CSRF by issuing a token that must accompany every state-changing request, so an attacker's forged request fails without it. I'd typically disable CSRF only for stateless, token-authenticated APIs consumed by non-browser clients, since there's no session cookie to exploit in that case."