Access-Control-Allow-Credentials
首先介紹一下Access-Control-Allow-Credentials
這個響應頭字段:
Access-Control-Allow-Credentials
,標誌是否允許客戶端請求攜帶Credentials(憑證)。Credentials
可以是 cookies
, authorization headers
或 TLS client certificates
.(一般可能攜帶cookies
的情況比較多)。該響應頭只能是true
或者不設置!
當作爲對預檢請求(Option請求
)的響應的一部分時,它指示是否可以使用Credentials(憑證)
進行實際請求。請注意,簡單的GET
請求是沒有預檢的,所以若一個對資源的請求帶了Credentials
,如果這個響應頭(Access-Control-Allow-Credentials
)沒有隨資源返回,響應就會被瀏覽器忽視,不會返回到web內容,預檢請求也會因此拋出不能通過預檢的error。
需知
Access-Control-Allow-Credentials
頭 工作中與XMLHttpRequest.withCredentials
或Fetch API
中的Request() 構造器中的credentials 選項
結合使用。Credentials
必須在前後端都被配置(即the Access-Control-Allow-Credentials header
和 XHR
或Fetch request
中都要配置)才能使帶credentials
的CORS
請求成功. 必需請求和response header
都支持!!!
使用方式
XHR 使用 Credentials
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true; // 設置withCredentials爲true
xhr.send(null);
JQ 使用 Credentials
使用的話則設置withCredentials
爲true
不使用則爲false
,MDN中明確指出withCredentials
默認值爲false
,但是根據阮一峯的一篇相關文章中評論似乎實際情況中默認值不生效,
$.ajax({
type:"POST",
url: 'http://example.com/',
data: {},
xhrFields: {
withCredentials: true // 設置withCredentials爲true
},
crossDomain: true,
dataType: 'json',
success: successHandler
});
fetch 使用 Credentials
fetch
控制Credentials
的選項有三個:
- 請求時攜帶憑證:
credentials: 'include'
- 僅在同源時請求時攜帶憑證:
credentials: 'same-origin'
(瀏覽器默認值,在舊版本瀏覽器,例如safari 11依舊是omit,safari 12已更改) - 不在請求中包含憑證,
credentials: 'omit'
fetch(url, {
credentials: 'include'
})
response header
Access-Control-Allow-Credentials: true
注意
要注意,當設置了 Access-Control-Allow-Credentials
爲 true
時,Access-Control-Allow-Origin
不能爲*
,也是出於一種安全策略,比如:在cookie
中存取的是用戶的登錄信息,又不限制客戶端的請求來源,他人獲取到cookie
以後則可隨意發起請求,登錄該用戶賬號,損害用戶權益