CORS vs CSRF: Understanding the Difference
A clear explanation of Cross-Origin Resource Sharing (CORS) and Cross-Site Request Forgery (CSRF).
CORS and CSRF are often confused because they both involve the concept of "Cross-Origin" or "Cross-Site" interactions, but they address entirely different security concerns.
What is CORS?
CORS (Cross-Origin Resource Sharing) is a relaxation of the Same-Origin Policy. The Same-Origin Policy is a fundamental security mechanism in browsers that prevents a website on one domain from making requests to a different domain.
If you have a frontend at https://app.example.com and an API at https://api.example.com, the browser blocks requests by default. CORS is the mechanism (using HTTP headers) where the API tells the browser, "It's okay, I allow requests from app.example.com."
Key takeaway: CORS is a mechanism to allow cross-origin requests that would otherwise be blocked by the browser.
What is CSRF?
CSRF (Cross-Site Request Forgery) is an attack. In a CSRF attack, a malicious website tricks the user's browser into performing an unwanted action on a trusted site where the user is currently authenticated.
For example, if you are logged into your bank, and you visit a malicious site, that site might have a hidden form that submits a POST request to https://bank.com/transfer. Because your browser automatically attaches your session cookies to requests to bank.com, the bank thinks you made the request.
Key takeaway: CSRF is an exploit of the browser's automatic credential-sending behavior.
How They Relate (and Don't)
CORS does not protect against CSRF. In fact, misconfigured CORS (like Access-Control-Allow-Origin: * with credentials) can make certain attacks easier.
To protect against CSRF, you need:
- Anti-CSRF Tokens: Unique, unpredictable tokens required for state-changing requests.
- SameSite Cookies: Setting
SameSite=LaxorSameSite=Stricton your session cookies prevents the browser from sending them in cross-site requests.
You can configure secure CORS policies using our CORS Generator.