Understanding Same-Origin Policy and CORS: A Complete Guide
This article explains the fundamentals of the browser's same-origin policy, its security implications, how it restricts DOM, web data and network access, and provides a detailed overview of CORS, including simple requests, preflight checks, required headers, and best practices for safe cross-origin communication.
Introduction
Recently the author encountered a frequent front‑end interview question about POST requests, which touches many concepts; the following explains the topic in detail.
Same-Origin Policy
Browsers can load many resources (JavaScript, images, audio, video, etc.), but unrestricted access would lead to security problems such as:
Cross‑site scripting (XSS)
SQL injection
OS command injection
HTTP header injection
Cross‑site request forgery (CSRF)
etc.
These risks require security strategies, the most fundamental being the same‑origin policy.
The same‑origin policy restricts how a document or its scripts can interact with resources from another origin.
Two URLs are considered same‑origin when their protocol, host, and port are identical.
Protocol: The system that defines how data is exchanged, e.g., HTTP, HTTPS.
Host: The computer or device connected to a network that provides resources and services.
Port: The endpoint for communication between processes on a host.
Example comparison of URLs:
http://test.home.com:8080/dir/page.htmlThe same‑origin policy manifests in three areas: DOM, Web data, and Network.
DOM access restriction: Scripts cannot directly access the DOM of a page from a different origin, preventing malicious data extraction.
Web data restriction: XMLHttpRequest or Fetch can only request resources from the same origin, helping prevent CSRF attacks.
Network communication restriction: Browsers block cross‑origin network responses unless the server explicitly permits them.
Therefore browsers restrict cross‑origin XHR and Fetch requests unless CORS headers are used.
CORS
Browsers may block the response of a cross‑origin request even if the request is sent; this is where CORS comes into play. CORB (Cross‑Origin Read Blocking) further prevents malicious code from accessing cross‑origin data before it reaches the rendering process.
CORB is a security mechanism that stops malicious code from reading cross‑origin responses by filtering resources before they are rendered.
For example, an AJAX request to another domain may succeed, but if the browser detects potentially dangerous data, it will block script access.
CORS (Cross‑Origin Resource Sharing) allows controlled cross‑origin requests by having the server include specific HTTP headers.
The server indicates allowed origins in the response header; browsers first send a preflight OPTIONS request for non‑simple requests.
Simple Request
A request that does not trigger a preflight is called a simple request. It must meet all of the following conditions:
HTTP method limited to GET, HEAD, or POST.
Custom headers limited to a small whitelist (Accept, Accept‑Language, Content‑Language, Last‑Event‑ID, Content‑Type with values application/x-www-form-urlencoded, multipart/form-data, or text/plain, and a few others such as DPR, Download, Save‑Data, Viewport‑Width, Width).
No use of ReadableStream objects.
No custom request headers; no event listeners on XMLHttpRequestUpload objects.
Preflight Request
Non‑simple requests trigger an additional HTTP OPTIONS request, called a preflight request, to determine whether the actual request is safe.
Example: deleting a record on a site first sends a preflight request.
Access-Control-Request-Method: Specifies the HTTP method the actual request will use (e.g., POST).
Access-Control-Request-Headers: A comma‑separated list of additional headers the actual request will send (e.g., content-type, x-secsdk-csrf-token).
access-control-allow-origin: Indicates which origin may access the resource (e.g., https://xxx.cn or *).
access-control-max-age: Optional field that defines how long the preflight response can be cached (e.g., 86408 seconds).
When the server approves, it includes Access-Control-Allow-Origin in the response, and subsequent actual requests behave like simple requests.
Credentials and Wildcards
When a request includes credentials (e.g., cookies), the server must not set Access-Control-Allow-Origin to *; it must specify a concrete origin. Likewise, Access-Control-Allow-Headers and Access-Control-Allow-Methods should list explicit values instead of using a wildcard, to prevent abuse.
Full Request Flowchart
Summary
A preflight request is an automatic OPTIONS request sent by the browser during CORS to ensure security and allow the server to decide whether to permit the cross‑origin request.
Cross‑origin requests are blocked by default; the same‑origin policy applies unless CORS is used. The preflight includes headers such as Origin and Access-Control-Request-Method. If the server responds with appropriate Access-Control-Allow-Origin and related headers, the browser proceeds with the actual request.
Using the preflight mechanism effectively mitigates security risks associated with cross‑origin requests, protecting user data and privacy.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
