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

Abd*_*UMI 1 javascript cookies credentials httpresponse cors

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

1.第一次尝试:

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

  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
          });
Run Code Online (Sandbox Code Playgroud)

- 客户端 :

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

2.第二次尝试:( withCredentials)

-服务器端 :

 //Append another response' header 
  response.header('Access-Control-Allow-Credentials','true'); 
Run Code Online (Sandbox Code Playgroud)

-客户端 :

// Before xhttp.send , I add another instruction : 
 xhttp.withCredentials=true;
Run Code Online (Sandbox Code Playgroud)

3.第三次尝试:

- 服务器端 :

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

- 客户端 :

 // Nothing is appended  
Run Code Online (Sandbox Code Playgroud)

结论:

通过所有这些尝试,xhttp.getResponseHeader('Set-Cookie')仍然会返回null:

  • Set-Cookie被分配给响应头:Access-Control-Expose-Headers.
  • 我在浏览器控制台(Inspector)上看到了cookie:

在此输入图像描述

rob*_*lep 7

TL; DR:Set-Cookie标题是完全禁止的:即使包含它,也无法访问它Access-Control-Expose-Headers.但是,一旦设置好,并且没有标记cookie httpOnly,您应该能够通过它访问它document.cookie.

TMI如下:

如此处所述,

响应通常会通过解析Access-Control-Expose-Headers标头来获取其CORS公开的标头名称列表集.CORS过滤响应使用此列表来确定要公开的标头.

什么是CORS过滤响应,则记录在这里:

CORS过滤响应是类型为"cors"的过滤响应,标题列表排除了内部响应的标题列表中的任何标题,其名称不是CORS安全的响应标题名称,给定内部响应的CORS公开标题名称列表,以及预告片是空的.

随后在此处记录已安全的标题:

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

列表中的任何值都不是禁止的响应标头名称.

最后,此处列出了禁止响应标头名称列表:

  • Set-Cookie
  • Set-Cookie2