简体   繁体   中英

Setting and getting a cookie back from a javascript tag request

I have the following situation:

  1. Javascript tag with src=domain1.com in another_domain.com page
  2. Javascript tag returns a cookie header and script content from domain1.com server
  3. Script content collects data and send it via request to domain1.com

I want to be able to set a cookie in the point 2 and recover it in the point 3. I've been able to set the cookie by returning a Set-Cookie header like this:

set-cookie: cookieName="cookieValue";Version=1;Domain=domain1.com;Path=/;SameSite=None;Max-Age=600;Secure

But I am not able to recover it in the request in the point 3, as the cookie is not sent with the request.

So, two questions at this point:

  1. Do I need to manually send the cookie in the second request? When tested doing redirects, the cookie header is "autoattached" to the second request and I'm able to recover it, but this is not happening with the requests from the javascript tag.

  2. I am only able to set a cookie in https (Secure cookie) and with SameSite=None from the script? When tried without Secure and SameSite=None or in an http environment, the cookie was not set and a cross-site error was thrown by the developer console.

Thanks for reading.

There are several things to consider here. First of all we have to note that we are facing a case of cross domain communications.

If you need to send in the step 3 the Cookie set by the server in the step 2, you have to explicitly configure it when making the request. In case you are using XMLHTTPRequest you have to set up withCredentials to true, here is the docs . If you are using fetch take a look at Request credentials .

As it's a cross domain communication, make sure your CORS headers are properly configured. When the request credentials mode is "include" you will need to set the Access-Control-Allow-Origin header to something valid and not a wildcard "*" . You will also need Access-Control-Allow-Credentials to true , check it here .

With this configuration, the cookie will be "autoattached" (as per your words) in the third step. You can't set a cookie via JS on a cross-domain setting for security reasons, see this response .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM