由 Credentials 引起的cors跨域問題

Access-Control-Allow-Credentials

首先介紹一下Access-Control-Allow-Credentials這個響應頭字段:

Access-Control-Allow-Credentials,標誌是否允許客戶端請求攜帶Credentials(憑證)Credentials可以是 cookies, authorization headersTLS client certificates.(一般可能攜帶cookies的情況比較多)。該響應頭只能是true或者不設置!

當作爲對預檢請求(Option請求)的響應的一部分時,它指示是否可以使用Credentials(憑證)進行實際請求。請注意,簡單的GET請求是沒有預檢的,所以若一個對資源的請求帶了Credentials,如果這個響應頭(Access-Control-Allow-Credentials)沒有隨資源返回,響應就會被瀏覽器忽視,不會返回到web內容,預檢請求也會因此拋出不能通過預檢的error。

需知

Access-Control-Allow-Credentials頭 工作中與XMLHttpRequest.withCredentialsFetch API中的Request() 構造器中的credentials 選項結合使用。Credentials必須在前後端都被配置(即the Access-Control-Allow-Credentials headerXHRFetch request中都要配置)才能使帶credentialsCORS請求成功. 必需請求和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

使用的話則設置withCredentialstrue不使用則爲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-Credentialstrue 時,Access-Control-Allow-Origin 不能爲*,也是出於一種安全策略,比如:在cookie中存取的是用戶的登錄信息,又不限制客戶端的請求來源,他人獲取到cookie以後則可隨意發起請求,登錄該用戶賬號,損害用戶權益

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章