Type something to search...
Fetch API 沒有傳送 cookies

Fetch API 沒有傳送 cookies

  • Web
  • 25 May, 2022

最近遇到一個案例,用戶明明有登入,但是打 API 時,卻因為沒有登入而噴錯。

在追查 HTTP Request/Response 時,眼尖的同事發現 Request Headers 根本沒有帶上 cookies,所以伺服器因為沒有 session 登入的資訊,所以才會當成 Client 端還沒登入。但奇怪的是 Client 端的網頁明明就是登入狀態。還有另一個線索是用戶的 Chrome 瀏覽器是很舊的版本。

後來透過一些關鍵字追查,追到這個 Stack Overflow 的留言 。原來是因為前端是使用 fetch 打 API,fetch 在舊版跟新版的預設行為不一樣,舊版是預設不帶 cookies(credentials: 'omit'),新版改掉了這個預設行為(credentials: 'same-origin')。所以如果沒有給 credentials 參數,就會使用預設值,造成舊版跟新版瀏覽器行為不一樣。

可以看到 fetch polyfill 這段說明

The default for credentials wasn’t always the same, though. The following versions of browsers implemented an older version of the fetch specification where the default was “omit”: Firefox 39–60 Chrome 42–67 Safari 10.1–11.1.2 If you target these browsers, it’s advisable to always specify credentials: 'same-origin' explicitly with all fetch requests instead of relying on the default

還有 mozilla 的 Fetch API

fetch 不會傳送 cookies,除非你有設定 credentials 的 init option (en-US)。 (Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)

Fetch Standard 這個 PR

Make fetch() use “same-origin” credentials by default

References

Related Posts

Chrome, AWS S3 and CORS
Chrome, AWS S3 and CORS

前陣子與公司的其他夥伴一起找出了偶發的 CORS 原因,紀錄一下 如果一個網站內有包含對同一個 URL 的載入,但是有兩種方式,一種是從 HTML document 載入,另一種是用 xhr 存取,並且 Chome 有開啟 cache,就有可能會遇到。 重現問題 例如下面這個簡單的範例,用兩種方式從 AWS cloudfont 抓取圖片,CDN 的來源是 AWS S3

read more
玩玩看 KKBOX 與 Spotify 的 OAuth 2.0
玩玩看 KKBOX 與 Spotify 的 OAuth 2.0

心血來潮想玩看看 KKBOX 的 Open API,也一起測試了 Spotify 的部分。這次主要是試試看 OAuth 2.0 Authorization Code Flow 的授權流程,過程都是利用 Postman 來操作。 <LinkCard url="https://developer.spotify.com/documentation/general/guides/authoriza

read more
玩玩看 Spotify 的 Authorization Code Flow with PKCE
玩玩看 Spotify 的 Authorization Code Flow with PKCE

看到 Spotify 有支援另外一種 Authorization Code Flow,叫做 Authorization Code Flow with Proof Key for Code Exchange (PKCE),來玩玩看 Authorization Code Flow with PKCE 跟 Authorization Code Flow 的差異在於。為了怕使用者的 code 被中間人竊

read more