Cross-Domain Cookies

后端 未结 15 2893
抹茶落季
抹茶落季 2020-11-21 21:56

I have two webapps WebApp1 and WebApp2 in two different domains.

  1. I am setting a cookie in WebApp1 in the HttpResponse.
  2. How to read the same cookie fro
15条回答
  •  天命终不由人
    2020-11-21 22:32

    Yes, it is absolutely possible to get the cookie from domain1.com by domain2.com. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.

    First, on the server side you need to have the following headers:

    header("Access-Control-Allow-Origin: http://origin.domain:port");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: GET, POST");
    header("Access-Control-Allow-Headers: Content-Type, *");
    

    Within the PHP-file you can use $_COOKIE[name]

    Second, on the client side:

    Within your ajax request you need to include 2 parameters

    crossDomain: true
    xhrFields: { withCredentials: true }
    

    Example:

    type: "get",
    url: link,
    crossDomain: true,
    dataType: 'json',
    xhrFields: {
      withCredentials: true
    }
    

提交回复
热议问题