Intermediate Security

CORS & Same-Origin Policy

Cross-origin requests, preflight, and security implications.

Cross-Origin Resource Sharing

CORS is a security feature that controls how web pages can request resources from different origins.

Same-Origin Policy

Browsers block requests to different origins by default. An origin is defined by: protocol + host + port.

https://example.com:443/path
  └─ protocol  └─ host └─ port

CORS Headers

Access-Control-Allow-Origin: https://mysite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

Preflight Requests

Complex requests trigger an OPTIONS preflight:

  • Non-simple methods (PUT, DELETE)
  • Custom headers
  • Content-Type other than form-data/text

Common Mistakes

  • Using Access-Control-Allow-Origin: * with credentials
  • Reflecting Origin header without validation
  • Exposing sensitive data cross-origin