此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
Access-Control-Allow-Credentials 標頭
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
HTTP Access-Control-Allow-Credentials 回應標頭告訴瀏覽器伺服器是否允許在跨來源 HTTP 請求中包含憑證。
憑證包括 Cookie、傳輸層安全性協定(TLS)用戶端憑證,或包含使用者名稱和密碼的驗證標頭。預設情況下,這些憑證不會在跨來源請求中傳送,這麼做可能會使網站容易受到跨站請求偽造(CSRF)攻擊。
用戶端可以透過以下幾種方式要求在跨站點請求中包含憑證:
- 使用
fetch(),將credentials選項設定為"include"。 - 使用
XMLHttpRequest,將XMLHttpRequest.withCredentials屬性設定為true。 - 使用
EventSource(),將EventSource.withCredentials屬性設定為true。
當包含憑證時:
- 對於預檢請求:預檢請求不包含憑證。如果伺服器對預檢請求的回應將
Access-Control-Allow-Credentials標頭設定為true,則實際請求將包含憑證;否則,瀏覽器會回報網路錯誤。 - 對於非預檢請求:請求將包含憑證,且如果伺服器的回應未將
Access-Control-Allow-Credentials標頭設定為true,瀏覽器會回報網路錯誤。
語法
http
Access-Control-Allow-Credentials: true
指令
true-
伺服器允許在跨來源 HTTP 請求中包含憑證。這是此標頭唯一有效的值,且區分大小寫。如果你不需要憑證,請完全省略此標頭,而不是將其值設定為
false。
範例
允許憑證:
http
Access-Control-Allow-Credentials: true
使用 fetch() 並包含憑證:
js
fetch(url, {
credentials: "include",
});
使用 XMLHttpRequest 並包含憑證:
js
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/", true);
xhr.withCredentials = true;
xhr.send(null);
規範
| Specification |
|---|
| Fetch> # http-access-control-allow-credentials> |
瀏覽器相容性
Loading...