引言
由於默認情況下瀏覽器對跨域請求不允許攜帶Cookie,所以這次開發再與前端同學在權限驗證這塊踩了好多坑,故將一些教訓寫下來,共勉!
CROS
在 2014 年 W3C 發佈了 CORS Recommendation 來允許更方便的跨域資源共享,同時CORS也允許我們使用額外的相應頭字段來允許跨域發送Cookie。
模擬前端代碼
設置withCredentials
爲true
即可讓該跨域請求攜帶 Cookie。 注意攜帶的是目標頁面所在域的 Cookie。以JQuery示例
$.ajax({
type: "GET",
url: "http://localhost:8080/seek/userinfo/#{xxxxx}",
async:false,
xhrFields: {
withCredentials: true
},
success: function(msg){
alert(msg.msg);
}
});
模擬後端代碼
此處還需要設置服務器接受跨域發送的Cookie。 否則會被瀏覽器的同源策略擋住:
服務器主要是設置response access-control-allow-credentials爲"true"
, 即可允許跨域請求攜帶 Cookie。
相關代碼如下:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token , Authorization"); response.setHeader("Access-Control-Allow-Credentials", "true");;
注意要點
跨域發送 Cookie 還要求 Access-Control-Allow-Origin
不允許使用通配符事實上不僅不允許通配符,而且只能指定單一域名
原文如下:
If the credentials flag is true and the response includes zero or more than one Access-Control-Allow-Credentials header values return fail and terminate this algorithm. –W3C Cross-Origin Resource Sharing
我採取的策略是request.getHeader(“Origin”)每次都獲取請求的源,但是這樣做的缺點也是很多的,主要就是不安全,任意請求攜帶Cookie都可以接受,最好的就是服務端可以維護一個接受Cookie的Origin列表,驗證Origin後在將其設置爲Access-Control-Allow-Origin的值。
結束語
在正確配置後就可以跨域發送Cookie進行客戶端與服務端之間相關的一些會話了,當然如果直接就是同一域的話,那就肯定沒這些問題啦,有時間再在這塊深入一下^_^!