Access-Control-Expose-Headers 不允许 JS 客户端读取 cookie

Access-Control-Expose-Headers does not work to allow JS client side to read cookies

我对 CORS 服务器进行了 AJAX 调用,我多次尝试能够使用 javascript 客户端读取响应返回的 cookie,但是徒劳无功。

1。第一次尝试:

- 服务器端(node.js 由 express 提供支持):

  response.header('Access-Control-Allow-Origin', '*');
  response.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Set-Cookie');
  response.header('Access-Control-Expose-Headers', "Set-Cookie");

 //------SET COOKIES
  response.cookie('SessionId', GeneratorId(64), {
            maxAge:3600000,
            httpOnly:flase // i disable httpOnly ==> does not work
          });

- 客户端:

var xhttp=new XMLHttpRequest();
xhttp.open("POST", "http://localhost:9090/api/map", true);
xhttp,send(`{layer:1}`);

2。第二次尝试:(withCredentials)

-服务器端:

 //Append another response' header 
  response.header('Access-Control-Allow-Credentials','true'); 

-客户端:

// Before xhttp.send , I add another instruction : 
 xhttp.withCredentials=true;

3。第三次尝试:

- 服务器端:

//Avoid the wildcard on Access-Control-Allow-Origin =>Replace the first header by :
response.header('Access-Control-Allow-Origin', request.get('Origin'));

- 客户端:

 // Nothing is appended  

结论:

经过所有这些尝试,xhttp.getResponseHeader('Set-Cookie') 仍然 returns null 甚至 :

TL;DR:Set-Cookie header 完全是 off-limits:您无法访问它,即使您将它包含在 Access-Control-Expose-Headers 中也是如此。但是,一旦它被设置,并且 cookie 没有被标记为 httpOnly,您应该能够通过 document.cookie.

访问它

TMI 如下:

如文档所述here

A response will typically get its CORS-exposed header-name list set by parsing the Access-Control-Expose-Headers header. This list is used by a CORS filtered response to determine which headers to expose.

什么是 CORS 过滤响应,记录在案 here:

A CORS filtered response is a filtered response whose type is "cors", header list excludes any headers in internal response's header list whose name is not a CORS-safelisted response-header name, given internal response's CORS-exposed header-name list, and trailer is empty.

安全列表 header 随后被记录 here:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

Any value in list that is not a forbidden response-header name.

最后列出了禁止response-header名字的列表here:

  • Set-Cookie
  • Set-Cookie2