What is the difference between CORS and CSRF (Cross-Site Request Forgery), and how does CORS relate to (but not fully prevent) CSRF?
Short answer
CSRF exploits the browser's automatic inclusion of credentials (cookies) on requests to any site, tricking a user's browser into making an unwanted authenticated request to a target site from a malicious page, regardless of CORS.
Advertisement
AModel answer
CSRF exploits the browser's automatic inclusion of credentials (cookies) on requests to any site, tricking a user's browser into making an unwanted authenticated request to a target site from a malicious page, regardless of CORS. CORS actually offers some incidental protection against CSRF for APIs, since a properly restrictive CORS policy prevents a malicious site's JavaScript from reading the response of a cross-origin request (though the request may still fire and take effect server-side) -- but CORS alone is not a complete CSRF defense, since simple form-based CSRF attacks (not requiring the attacker to read the response) can still succeed; dedicated anti-forgery tokens remain necessary for full protection.
// A malicious site can still trigger this request (CSRF), even with strict CORS,
// because a simple form POST doesn't require reading the response:
// <form action="https://bank.com/transfer" method="POST">
// <input type="hidden" name="amount" value="10000">
// </form>
// CORS prevents the attacker's JS from READING the response, but the transfer may still happenReal-world example
A security review clarifies to the team that their strict CORS policy protects their API from cross-origin JavaScript reading sensitive responses, but doesn't fully protect a cookie-authenticated form-based endpoint from CSRF, which still requires anti-forgery tokens.
Likely follow-ups
- How do anti-forgery tokens (like ASP.NET Core's built-in ones) provide CSRF protection CORS can't?
- Why is SameSite=Strict/Lax cookie configuration also relevant here?
Related topics