HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
3 Topics
Chapter•150 Minutes

CORS, CSRF and Browser Security

Understand browser-enforced API security boundaries and the difference between CORS and CSRF.

Same-Origin Policy

Browsers restrict how scripts from one origin interact with resources from another origin. An origin is defined by scheme, host, and port.

For example, https://app.example.com and https://api.example.com are different origins even though they share a parent domain.

The browser's same-origin policy is a security boundary. CORS provides a controlled mechanism through which servers can tell browsers which cross-origin requests may be allowed.

Origin Components
Scheme: https
Host: api.example.com
Port: 443

Cross-Origin Resource Sharing

CORS is a browser security mechanism controlled by HTTP response headers.

A server can respond with Access-Control-Allow-Origin to indicate which origin may read the response through browser APIs.

Some cross-origin requests trigger a preflight OPTIONS request. The browser asks whether the server permits the intended method and headers. The server responds with appropriate CORS headers.

CORS is primarily a browser enforcement mechanism. It does not replace authentication or server-side authorization.

CORS Preflight

Cross-Site Request Forgery

CSRF occurs when a malicious site causes a victim's browser to send an authenticated request to another site, relying on automatically attached credentials such as cookies.

Cookie-authenticated APIs therefore require CSRF considerations. Defenses include SameSite cookies, CSRF tokens, origin checks, and appropriate architectural choices.

Bearer tokens manually attached by JavaScript are not automatically included by the browser in the same way as cookies, but storing tokens in browser-accessible storage introduces other risks such as token theft through XSS.

CORS Does Not Prevent CSRF

CORS controls whether browser scripts can read cross-origin responses. CSRF concerns unauthorized state-changing requests made with automatically attached credentials.