温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - ASPXAUTH cookie not being stored after CORS request
cookies javascript wcf

javascript - CORS请求后未存储ASPXAUTH cookie

发布于 2020-04-08 10:09:51

我被要求编写一个javascript / HTML前端以连接到一组WCF服务。我可以使用Postman来登录服务,并且可以看到在有效登录中设置了两个cookie .ASPXAUTHASP.NET_SessionId

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

但是,Cookie不会存储在浏览器中,因此由于缺少Cookie凭据而导致对服务器的后续请求失败。

客户端应用程序与服务器(http:// localhost:3101在不同的域(https:// localhost:44357)上,因此正在使用CORS。使用进行客户端调用,它是包装器我正在使用应该添加标题。您可以看到它被包括在内:aurelia-http-clientXMLHttpRequest.withCredentials()credentials: true

在此处输入图片说明

为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?

查看更多

提问者
RHarris
被浏览
87
RHarris 2020-02-01 05:33

在玩游戏时,我发现将Access-Control-Allow-Credentials标头移到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(...)
    {
       ...
    }
}