跨域種cookie的問題
阿新 • • 發佈:2020-08-21
如a.123.com跨域訪問b.123.com/request,b.123.com伺服器使用nginx允許跨域,Access-Control-Allow-Origin:*
如果a、b服務不在同一個伺服器,前臺頁面請求報錯資訊為:
Access to XMLHttpRequest at 'http://b.123.com'
from origin 'http://a.123.com' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
對應ajax請求為:
$.ajax({
url : 'http://b.123.com/request',
data : data,
dataType: 'json',
type : 'POST',
xhrFields: {
withCredentials: true
},
crossDomain: true,
...
此時,應取消nginx設定的跨域*,改成程式碼端設定。且程式碼伺服器端通過在響應 header 中設定
response.setHeader("Access-Control-Allow-Credentials", "true");
來執行客戶端攜帶證書式訪問。通過對 Credentials 引數的設定,就可以保持跨域 Ajax 時的 Cookie。
伺服器端Access-Control-Allow-Credentials = true
時,Access-Control-Allow-Origin
的值不能為'*'
,應設定為發起請求的地址。
// a.com發來的請求
response.setHeader("Access-Control-Allow-Origin", a.123.com);
b伺服器在設定cookie時,需設定
cookie.setPath("/");
cookie.setDomain("123.com");
否則設定的cookie無法生效。