--- title: CORS tags: image: --- # CORS :::info * Cross-Origin Resource Sharing (CORS) is an ++HTTP-header based mechanism++ that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. * CORS also relies on a mechanism by which **browsers** make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request. ::: > 跨來源請求擋的其實是 response,而不是 request。 ![](https://i.imgur.com/7rGSX5R.png) [toc] <br/> ## WHY - 為什麼會發生 CORS? * CORS 的這個錯誤是出在 "跨來源呼叫 API" * 何謂跨來源 (cross origin) * 舉例來說,就是從 A 來源去拿 B 來源的東西,來源不同,就是跨來源。而這個來源指的是 "發送 request 的來源" * https://tw.yahoo.com 與 https://google.com 兩者就是不同源的例子 fyi - origin:scheme + host + port <br/> ## HOW - 如何解決 CORS 問題? * 後端設置 CORS header * header 的名稱: 'Access-Control-Allow-Origin' * header 的內容: 你想放行的 Origin ```javascript const express = require('express'); let myapp = express(); myapp.get('url', function (req, res) { res.set('Access-Control-Allow-Origin', 'http://localhost:8081'); res.end('hello world'); }); ``` header 內無法放入多個 origin,你只能放一個,或是你可以選擇放 *,就代表允許任何 origin 的意思。如果想要針對多個 origin,server 那邊就必須做一些額外處理。 ```javascript myapp.get('url', function (req, res) { res.set('Access-Control-Allow-Origin', '*'); res.end('hello world'); }); ``` ** 只有在後端設置才有用 <br/> ## Security - 跨來源的安全性問題 安全疑慮發生的條件 1. 後端對於 `Access-Control-Allow-Origin` header 的檢查不嚴謹。 2. cookie 沒有限制 sameSite 才能使用。 3. 使用者帶著 cookie 瀏覽第三方網頁。 <br/> ## Proxy Server <br/><br/> ## References * [mdn wed doc - CORS]( ]https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) * Hui CORS 系列文章 * [輕鬆理解 Ajax 與跨來源請求](https://blog.huli.tw/2017/08/27/ajax-and-cors/) * [CORS 完全手冊(一):為什麼會發生 CORS 錯誤?](https://blog.huli.tw/2021/02/19/cors-guide-1/) * [CORS 完全手冊(二):如何解決 CORS 問題?](https://blog.huli.tw/2021/02/19/cors-guide-2/) * [CORS 完全手冊(三):CORS 詳解](https://blog.huli.tw/2021/02/19/cors-guide-3/) * [CORS 完全手冊(四):一起看規範](https://blog.huli.tw/2021/02/19/cors-guide-4/) * [CORS 完全手冊(五):跨來源的安全性問題](https://blog.huli.tw/2021/02/19/cors-guide-5/) * [CORS 完全手冊(六):總結、後記與遺珠](https://blog.huli.tw/2021/02/19/cors-guide-6/) * [理论与实践相结合彻底理解CORS](https://segmentfault.com/a/1190000037765341) * [Hacking CORS](https://github.com/lvrosa/hacking-cors) * https://www.thehacker.recipes/web/config/http-headers/cors-cross-origin-resource-sharing *