Facebook Pixel

CORS vs CSRF vs CSP: What's the Difference?

Three web security concepts that are often confused. Here is the difference.

CORS vs CSRF vs CSP

CORS (Cross-Origin Resource Sharing)

  • What: allows servers to opt-in to cross-origin requests.
  • Who: browser enforces, server configures.
  • Purpose: enable legitimate cross-origin API calls.
  • Fix: server headers (Access-Control-Allow-Origin).

CSRF (Cross-Site Request Forgery)

  • What: an attacker tricks a user into making a request they did not intend.
  • Who: attacker exploits the user's authenticated session.
  • Purpose: prevent unauthorized actions.
  • Fix: CSRF tokens, SameSite cookies, check Origin header.

CSP (Content Security Policy)

  • What: restricts what resources (scripts, styles, images) a page can load.
  • Who: browser enforces, server configures via headers.
  • Purpose: prevent XSS (cross-site scripting).
  • Fix: Content-Security-Policy header with allowed sources.

Summary

FeatureCORSCSRFCSP
ProblemCross-origin APIUnauthorized actionsXSS
MechanismServer headersTokens, SameSiteCSP header
Enforced byBrowserServer + BrowserBrowser

The Takeaway

CORS: allows cross-origin API calls (server opt-in). CSRF: prevents unauthorized actions (tokens, SameSite cookies). CSP: prevents XSS (restrict resource sources). They are different security mechanisms for different problems.

CORS allows servers to opt-in to cross-origin requests (enable legitimate API calls). CSRF is an attack where a malicious site tricks a user into making unwanted authenticated requests. CORS enables; CSRF attacks. They are different security concerns.

CORS controls cross-origin API requests (server opt-in via headers). CSP controls what resources a page can load (prevent XSS via Content-Security-Policy header). CORS is about API access; CSP is about content loading.

No. CORS is about allowing cross-origin requests, not preventing them. CSRF prevention requires: SameSite cookies, CSRF tokens, or checking the Origin/Referer header on the server. CORS and CSRF are separate security concerns.

A browser security mechanism that restricts what resources (scripts, styles, images, fonts) a page can load. Configured via the Content-Security-Policy header. Prevents XSS by blocking inline scripts and restricting sources.

CORS allows legitimate cross-origin API calls. CSRF prevents attackers from tricking users into unwanted requests. CSP prevents XSS by restricting resource sources. Together, they form a layered security model: API access (CORS), request authenticity (CSRF), and content safety (CSP).

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.