IFrame没有读取cookie后调用JQuery Ajax函数

时间:2016-11-14 22:49:36

标签: jquery asp.net ajax iframe cookies

我的网站 MAIN http://localhost:63085/),其中嵌入了iframe,iframe源来自其他主机网站 BRANCH http://localhost:50725/)。 iframe中的页面需要cookie才能工作(因为它使用表单身份验证)。

我在分支机构网站上设置了一个API,用于对用户进行身份验证并在响应中发回cookie。主网站将调用API,然后在iframe中加载默认页面(在分支下托管)。

默认页面需要表单身份验证cookie。我认为iframe应该自动读取cookie(因为它们都在localhost下)。但是,默认页面中的用户未经过身份验证,从不读取cookie。

这是Main Branch Site的Ajax功能:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="row">
    <div class="row">
        <iframe id="frmCompas" width="800" height="800"></iframe>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function () {
        console.log("ready!");
        authUser();
    });

    function authUser() {

        $.ajax({
            url: 'http://localhost:50725/api/auth?name=h&pass=1',
            type: 'POST',
            dataType: 'json',
            success: function (data) { //auth user through the web api to generate an authentication Cookie
                frmCompas.src = "http://localhost:50725/Default.aspx"
            },
            error: function () {
                console.log('Error in Operation');
            }
        });

    }

</script>

如您所见,在分支下调用API(http://localhost:50725)后,我会在iframe中加载默认页面。

我的问题是,在调用主站点时,返回的cookie在读取默认页面时不会被读取并随请求一起发送:

测试第一个案例:致电主网站

  1. 从主站点调用Auth API
  2. enter image description here

    1. 在IFrame中渲染默认页面: enter image description here
    2. 我还尝试直接在url中浏览分支站点默认页面(它也没有获得该cookie)并且没有通过身份验证。

      测试第二种情况:在单独的网址中调用Auth Api

      API:返回cookie:“ 36FED3D72417 ..

      现在,当我浏览主网站时,检查流量时会发生什么:

      1. 调用Localhost:cookie在开头的请求中关联
      2. enter image description here

        1. 致电API:
        2. enter image description here

          1. 在iframe中调用Main / Default.aspx:
          2. enter image description here

            查找 iframe读取在主站点外部调用时由api生成的cookie。

            如何在第一个测试用例中解决此问题并使iframe可以读取cookie?

1 个答案:

答案 0 :(得分:0)

问题出在ajax函数本身。所以,我试图获取cookie并将其重写到浏览器中。但是,我无法使用指示here Set-Cookie 标头执行此操作。

xhr.getResponseHeader('Set-Cookie');

因此,我修改了分支站点下的API,将respone体中的cookie数据作为json返回,而不是将其放在响应头中。

API:

   [HttpPost]
    public HttpResponseMessage Get(string name, string pass)
    {
        var resp = new HttpResponseMessage();

        if (name == "h" && pass == "1") //dummy data 
        {
            // Create the authentication ticket with custom user data.
            var serializer = new JavaScriptSerializer();

            Models.User u = new Models.User() { Id = 1, Name = "Test", Username = "h", Age = 31 };
            string userData = serializer.Serialize(u);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                  name,
                    DateTime.Now,
                    DateTime.Now.AddDays(2),
                    true,
                    userData,
                    FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new MyCustomCookie()
            {
                Name = FormsAuthentication.FormsCookieName,
                Value = encTicket,
                Days = "2"
            };

            return Request.CreateResponse(HttpStatusCode.OK, cookie);
        }

        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

这是来自API的 响应主体

{"Name":".MyAuthCookie","Value":"953020CCD5739418E2D3FB42AB00072..", "Days": 1}

然后在主站点的AJAX调用中:我获取json数据并使用javascript创建cookie:

    $(document).ready(function () {
        authUser();
    });

    function authUser() {
        $.ajax({
            url: 'http://localhost:50725/api/auth?name=h&pass=1',
            type: 'POST',
            success: function (data, status, xhr) {
                 // you need to also check the status to avoid creating a 
                 //useless cookie if the user was not authorized

                createCookie(data.Name, data.Value, data.Days);
                frmCompas.src = "http://localhost:50725/Default.aspx"
            },
            error: function () {
                console.log('Error in Operation');
            }
        });
    }

    function createCookie(name, value, days) {
         if (days) {
            var date = new Date();
             date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
          }
         else 
            var expires = "";

         document.cookie = name + "=" + value + expires + "; path=/";
     }
相关问题