A
A
Alice2021-05-04 00:44:06
PHP
Alice, 2021-05-04 00:44:06

Why are cookies not set when SPA calls via API to the server?

I have a React application hosted on mysite.com. It communicates via API with a server located on the host api.othermysite.com. Everything worked fine until it came to authorization and setting a session cookie on the client (browser).
The session cookie arrives from the api server, but is not set in any way, no matter what I do.
On the client, I send requests via axios with the following parameters:

const instance = axios.create({
    withCredentials: true,
    baseURL: (api.othermysite.com),
    headers: {
        'App-Name': (name),
        'Api-Key':  (key),
    },
})

The server is written in php. The response headers are:

$this->response->addHeader('Access-Control-Allow-Credentials: true');
        $this->response->addHeader('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        $this->response->addHeader('Access-Control-Allow-Origin: mysite.com" );
        $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, App-Name, Api-Key, Access-Control-Allow-Credentials');
        $this->response->addHeader('Cross-Origin-Resource-Policy: cross-origin');
        $this->response->addHeader('Content-Type: application/json');

The whole point of the API is to access it from different sources, but I can’t figure out how to save the session state on the client.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alice, 2021-05-04
@blonde_13

I've understood! In order for everything to work as I wanted, on the server side, when setting cookies in setcookie, add options SameSite=None, Secureand then the browser will set cookies.
But keep in mind that the option Securerequires work over the secure https protocol, so for local development in the Chrome browser, you need to disable checking this parameter.
chrome://flagsSet the SameSite by default cookies parameter to Disabled

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question