Reputation: 77
I have the following situation:
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:
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.
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.
Upvotes: 0
Views: 126
Reputation: 141
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.
Upvotes: 1