1. 程式人生 > >CORS跨域傳送Cookie

CORS跨域傳送Cookie

引言

由於預設情況下瀏覽器對跨域請求不允許攜帶Cookie,所以這次開發再與前端同學在許可權驗證這塊踩了好多坑,故將一些教訓寫下來,共勉!

CROS

在 2014 年 W3C 釋出了 CORS Recommendation 來允許更方便的跨域資源共享,同時CORS也允許我們使用額外的相應頭欄位來允許跨域傳送Cookie。

模擬前端程式碼

設定withCredentialstrue即可讓該跨域請求攜帶 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進行客戶端與服務端之間相關的一些會話了,當然如果直接就是同一域的話,那就肯定沒這些問題啦,有時間再在這塊深入一下^_^!