CORS 请求后未存储 ASPXAUTH cookie

ASPXAUTH cookie not being stored after CORS request

我被要求编写一个 javascript/HTML front-end 来连接到一组 WCF 服务。我可以使用 Postman 访问登录服务,我可以看到在有效登录时,设置了两个 cookie .ASPXAUTHASP.NET_SessionId

当我从我的 javascript 代码访问相同的服务时,我得到了 200 响应,并且在 Chrome 开发人员工具的网络部分,我可以看到 Set-Cookie header 在对两个 cookie 中的每一个的响应中。

但是,cookie 不会存储在浏览器中,因此对服务器的后续请求会失败,因为它们缺少 cookie 凭据。

客户端应用程序位于不同的域 (https://localhost:44357) than the server (http://localhost:3101),因此 CORS 正在发挥作用。客户端调用是使用 aurelia-http-client 进行的,它是 XMLHttpRequest 的包装器。我正在使用 .withCredentials(),它应该添加 credentials: true header。您可以看到它被包含在内:

服务器为 CORS 配置如下:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","https://localhost:44357");
    if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control","no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers","Content-Type,Accept,credentials");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials","true");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age","1728000");
    }
}

我错过了什么?为什么浏览器不存储来自 WCF 服务器的 cookie?

在尝试中,我发现将 Access-Control-Allow-Credentials header 移到 if 语句之外就可以了。

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",...)
    //Had to move this line outside of the if statement
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials","true");
    if(...)
    {
       ...
    }
}