Security for Engineers/Web & Browser Security

CSRF, CORS & Same-Origin Policy

Same-origin policy, CSRF tokens vs SameSite cookies, CORS preflight, and credentialed cross-origin requests.

3/5Overview: 30m

Same-origin policy

Browser restricts how documents from one origin (scheme + host + port) interact with another.

https://app.example.comhttps://api.example.com — different origins.

JS can't read cross-origin responses unless server allows via CORS.

CSRF — cross-site request forgery

Victim logged into bank.com; evil.com triggers form POST to bank.com with victim's cookies.

Defenses:

  • SameSite=Lax/Strict cookies — don't send on cross-site POST
  • CSRF token — server secret in form, validated on POST
  • Custom headersX-Requested-With or Authorization (not sent by simple forms)

APIs using Bearer tokens in header (not cookies) — CSRF risk lower.

CORS — not a security gate

CORS relaxes browser restriction for legitimate cross-origin frontends.

Access-Control-Allow-Origin: https://app.example.com Access-Control-Allow-Credentials: true

Misconception: CORS blocks attackers — wrong. Attackers use curl/server, not browser policy.

Misconfiguration: Allow-Origin: * with Credentials: true — invalid and dangerous patterns.

Preflight

Browser sends OPTIONS before non-simple requests (custom headers, JSON POST).

API must respond with allowed methods/headers.

Credentialed requests

SPA with cookies → need specific origin (not *), Allow-Credentials: true, matching cookie SameSite=None; Secure for cross-site.

Fullstack system design

Separate web and API subdomains — standard. Document CORS allowlist per environment; never * in prod with credentials.

Cross-reference: Communication → REST for API design; Networking for cookie + HTTP header mechanics.

Further Reading

Hands-On Tasks (Optional)

Security design drills — threat modeling, auth flows, and incident playbooks. Assumes Networking (TLS) fundamentals.

  • Debug a CORS failure

    SPA on app.example.com calls api.example.com with cookies. Browser blocks. List headers needed on API and cookie attributes on Set-Cookie.

    15m