Understanding Same-Origin Policy, CORS, and Preflight Requests
The article explains the fundamentals of the browser's same‑origin policy, the security risks it mitigates, how Cross‑Origin Resource Sharing (CORS) works—including simple and preflight requests—and best practices for handling credentials and header restrictions.
Web browsers allow many types of resources to be loaded, but unrestricted access can lead to security issues such as XSS, SQL injection, CSRF, and others. To protect user data, browsers enforce the same‑origin policy, which restricts interactions between documents that do not share the same protocol, host, and port.
The same‑origin policy limits three main areas: DOM access, web data (e.g., XMLHttpRequest or Fetch), and network communication. Scripts cannot read or manipulate the DOM of a page from a different origin, and cross‑origin network requests are blocked unless explicitly allowed.
Cross‑Origin Resource Sharing (CORS) provides a controlled way to relax these restrictions. A server can indicate permitted origins via the Access-Control-Allow-Origin header, and browsers will send a preflight OPTIONS request for non‑simple requests to verify the server’s policy before the actual request is made.
Simple requests are limited to the GET, HEAD, or POST methods, use only a small set of safe headers, and do not include a request body stream. If any of these conditions are not met, the browser performs a preflight request that includes Access-Control-Request-Method and Access-Control-Request-Headers to inform the server of the intended method and custom headers.
When credentials such as cookies are included, the server must not use a wildcard (*) for Access-Control-Allow-Origin ; it must echo back the specific requesting origin. Likewise, Access-Control-Allow-Headers and Access-Control-Allow-Methods should list explicit values rather than using a wildcard to avoid security risks.
After a successful preflight, the actual request proceeds with an Origin header, and the server’s response includes Access-Control-Allow-Origin (and optionally other CORS headers) to confirm the request is allowed.
In summary, the same‑origin policy is a core browser security mechanism, and CORS with its simple‑request and preflight flows provides a safe way to enable cross‑origin communication while protecting user data and privacy.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.