V
V
Vadym Masiuk2020-09-02 14:07:56
PHP
Vadym Masiuk, 2020-09-02 14:07:56

How to set cookies on cross-domain AJAX request?

There is a question about setting cross-domain / third-party / 3rd party or, as they say, cross-site cookies.
There are 2 domains (the names are simplified for better clarity and better understanding):

1. public.com (from here the form is sent to the 2nd AJAX domain)
2. 3rdparty.com (only accepts AJAX requests, written in PHP)

Both domains have full access, but they are on different servers/IP.
On the 2nd domain, it is also possible to set headers:

header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: https://public.com');

Q : What are some good options in 2020 to set $_COOKIE for the 3rdparty.com domain when a user visits public.com?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Shumov, 2020-09-02
@inoise

No. It's impossible. If you are doing a single login, then Single Sign On technologies are used here

K
Kano, 2020-09-03
@Kano

Almost exactly the same as before, but with a few additions.
The first thing to do is to completely switch to https (if we want it not to be lame in chrome).
Make an ajax request to 3rdparty.com so that it sets a cookie, before indicating the server to this request, it should respond with the necessary headers, for example:
req.withCredentials = true

Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: https://public.com
Vary: Origin

And of course set the cookie itself
Set-Cookie: {CookieName}={CookieValue}; Max-Age=63072000; Path=/; SameSite=None; Domain=.3rdparty.com; HttpOnly; Secure

I especially want to note the "Access-Control-Allow-Origin" header which should always have a specific value, no wildcards.
As well as the mandatory attributes of the "Set-Cookie" header - "SameSite=None" and "Secure"
This will not work on all devices under ios and, it seems, in the fire fox (cross-domain cookies are generally prohibited there if the user has not visited the site that sets the cookie in main browser window).

P
psiklop, 2022-02-05
@psiklop

Unfortunately, all the old methods have stopped working for me, they still work, but in few places.
There is one dreary, but 100% working way:
1. I open a window using the open method on another domain, making it as invisible as possible.
2. I read the cookie and pass it back via the postMessage method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question