XMLHttpRequest.withCredentials 解決跨域請求頭無Cookie的問題

查看原文html

XMLHttpRequest.withCredentials  屬性是一個Boolean類型,它指示了是否該使用相似cookies,authorization headers(頭部受權)或者TLS客戶端證書這一類資格證書來建立一個跨站點訪問控制(cross-site Access-Control)請求。在同一個站點下使用withCredentials屬性是無效的。ajax

此外,這個指示也會被用作響應中cookies 被忽視的標示。默認值是false。json

若是在發送來自其餘域的XMLHttpRequest請求以前,未設置withCredentials 爲true,那麼就不能爲它本身的域設置cookie值。而經過設置withCredentials 爲true得到的第三方cookies,將會依舊享受同源策略,所以不能被經過document.cookie或者從頭部相應請求的腳本等訪問。跨域

注: 永遠不會影響到同源請求瀏覽器

Note: 不一樣域下的XmlHttpRequest 響應,不論其Access-Control- header 設置什麼值,都沒法爲它自身站點設置cookie值,除非它在請求以前將withCredentials 設爲true。安全

 

總結: XMLHttpRequest.withCredentials 能夠是用來解決跨域請求時,因爲瀏覽器安全 策略,不會自動攜帶cookie到服務器的問題。服務器

 

Post請求實例:cookie

 

var xmlhttp
if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest()
} else {
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.open('POST', 'http://xxx/xxx/script', true)
xmlhttp.setRequestHeader('Content-type', 'application/json')
xmlhttp.withCredentials = true // 使外部腳本中的post請求頭攜帶當前域的Cookies
// 注意:這裏不能使用xmlhttp.setRequestHeader('Cookie', document.cookie),這樣設置是不安全的作法
// xmlhttp.setRequestHeader('Cookie', document.cookie) // error
xmlhttp.send(JSON.stringify(postData))

Get請求實例:app

var xmlhttp
if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest()
} else {
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.open('GET', 'http://example.com/', true)
xhr.withCredentials = true
xhr.send(null)

Ajax請求:post

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true
})

 

參考:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials

相關文章
相關標籤/搜索