← HTTP / Browser Protocols

WEB PROTOCOLS · 89

Same-Origin Policy / CORS:Browser 為什麼擋跨 Origin JavaScript

CORS 不是 server firewall,也不是「讓 API 變公開」。它是 Browser 對跨-origin script access 的一套協議。要 debug CORS,先把 origin 算對,再分 simple request、preflight、credential policy。

Learning outcomes

1. Origin = scheme + host + port

https://app.example.com
https://api.example.com

host 不同
→ cross-origin

Path/query 不參與 origin identity。

2. Same-Origin Policy 保護 Browser context

若任意網站 JavaScript 都能讀你登入銀行網站的 private response,風險極大。Browser 預設限制跨-origin讀取,再由 target server 透過 CORS headers 明確授權。

3. CORS response header

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

這是 server 對 Browser 說「這個 origin 可讀 response」。不是 server 在驗證 user permission。

4. Preflight

OPTIONS /courses
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

某些跨-origin request 前,Browser 先用 OPTIONS 詢問是否允許實際 method/headers。

5. Credentialed request 有更嚴格規則

若 request 涉及 cookies/credentials,server 需要正確的 allow-origin/credentials policy,不能把「任何 origin 都可讀」和 credential sharing 隨意混用。

Project checkpoint:Request Map v4

設定 app origin 與 api origin,畫出 GET 無 preflight 與 POST JSON 可能有 preflight 的完整 message sequence。

Browser
  ↓ OPTIONS
API
  ↑ CORS allow headers
Browser
  ↓ POST
API
  ↑ response

Debug evidence:Console 說被 CORS 擋

  1. 兩邊 origin 實際是什麼?
  2. 有沒有 OPTIONS request?
  3. Preflight status/headers?
  4. Actual response 有沒有 allow-origin?
  5. 是否 credential policy mismatch?

Knowledge check

  1. Path 不同會變 cross-origin 嗎?
  2. CORS 是否等於 authentication?
  3. Preflight 真正詢問什麼?
  4. 用兩組 URL 判斷是否 same-origin,並解釋。