Search code examples
phpajaxcookiescross-domainsetcookie

CORS Ajax Request: Set-Cookie failing


The CORS scheme is:

AJAX Call from: https://remotewebsite.com/

GET Request to http://localhost/?param=ThisIsImportant

I am using localhost because it still in development.

Request URL: http://localhost/?param=ThisIsImportant
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: strict-origin-when-cross-origin

Response Headers

Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 226
Content-Type: text/html; charset=UTF-8
Date: Mon, 27 Sep 2021 20:18:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=100
Pragma: no-cache
Server: Apache/2.4.48 (Win64) OpenSSL/1.1.1k PHP/8.0.8
Set-Cookie: PHPSESSID=00fg461kl112lctp7ooqr5mder; path=/
X-Powered-By: PHP/8.0.8

PHP Pseudo-code

session_start();
$_SESSION['hash'] = $_GET['param'];

If I enter in http://localhost and visit a script with:

session_start();
print_r($_SESSION);

Session is empty. If I check cookies in developer tools, PHPSESSID is different from the one on AJAX response.

I need set the PHPSESSID during AJAX response and kept, and be able to retrieve the SESSION['hash'] set on PHP during that AJAX request. Including in another scripts on localhost. Is that possible?


Solution

  • Found that the $.ajax request should contain

    withCredentials: true

    crossDomain: true

    on server-side, the script need:

    header('Access-Control-Allow-Credentials: true');
    session_set_cookie_params(["SameSite" => "none"]); //none, lax, strict
    session_set_cookie_params(["Secure" => "true"]); //false, true
    session_set_cookie_params(["HttpOnly" => "true"]); //false, true
    

    that's it.