Advertisement
Beginner .NET, CORS & Cross-Origin Resource Sharing

What is CORS, and why do browsers enforce it?

Short answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin (different scheme, domain, or port) than the one that served the page, unless the target server explicitly permits it via response headers.

Save .NET mock interview
Advertisement
AModel answer
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin (different scheme, domain, or port) than the one that served the page, unless the target server explicitly permits it via response headers. Browsers enforce this to prevent malicious sites from silently making authenticated requests to other sites on a user's behalf using the user's existing cookies/credentials -- it's a client-side (browser) enforced policy, not a server-side security boundary.
// Page served from https://myapp.com trying to call https://api.otherapp.com
fetch('https://api.otherapp.com/data')
  .then(r => r.json());
// Blocked by the browser unless api.otherapp.com's response includes
// Access-Control-Allow-Origin: https://myapp.com (or *)
Real-world example
A single-page app hosted at app.mycompany.com calling an API at api.mycompany.com (different subdomain = different origin) needs the API to explicitly configure CORS to allow requests from app.mycompany.com's origin.
Likely follow-ups
  • What exactly counts as a different 'origin' (scheme, host, port)?
  • Why is CORS enforced by the browser rather than the server itself?
Related topics