Video in progress
What is CSRF protection, when do you need it, and when is it safe to turn off?
CSRF is a foreign site sending a request through the user's browser with the user's cookie. If the session lives in a cookie, you need protection. For an API that works only with a token in the Authorization header, it is usually turned off.
📖 Answer
The attack: the user is logged in to a bank (has a session cookie), then opens a malicious site. That page has a hidden form:
<form action="https://bank.uz/transfer" method="post">
<input name="to" value="hacker"><input name="amount" value="1000000">
</form>
<script>document.forms[0].submit()</script>
The browser adds the cookie by itself, and the server thinks the request came from the user.
Spring Security asks for a random CSRF token on every state-changing request (POST/PUT/DELETE). A foreign site can't read it. Thymeleaf adds the token to forms automatically.
If authentication happens only through the Authorization: Bearer ... header, you can turn it off: the browser doesn't add that header by itself, so the attack doesn't work. But if an SPA stores the token in a cookie, that's still a cookie! Then you need CSRF (CookieCsrfTokenRepository) or a SameSite=Strict/Lax cookie.
SameSite=Lax (the default in modern browsers) stops many attacks, but don't treat it as your only defense: old browsers and endpoints that change state with GET are still at risk.
Sign up to mark studied questions and save your progress.