javascriptphpcorsheadercross-domain

I migrated my javascript client to another domain and now cross site call to php api are not sharing the same php session


For some time now I had to endpoint :

To make those work tohgether I needed a shared Php session. So for that I setted up everything like this :

Access-Control-Allow-Origin: https://client.a.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS

And it worked well.

Now, I want to move client from https://client.a.com to https://b.com

So I didn't change a thing in the client, but I change the api headers response to

Access-Control-Allow-Origin: https://b.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS

And it does not work at all. Everytime I send a new request from the client to the api it is a new PHP session.

Any idea what would be the trick, if there is one ? Cheers <3


Solution

  • Session cookies can be shared between subdomains, with the right configuration - presumably that's what has been happening up to now. But you can't share sessions across entirely different root domains.

    If you want to move the front-end to a new domain, e.g. b.com, without redesigning your software more substantially, a simple solution would be to move the backend to a subdomain of b.com, e.g. api.b.com.


    P.S. Longer-term: Ideally if you are designing an app with a totally separate client front-end and an API backend, it should be architected in a more stateless way so that it doesn't require the use of sessions in the first place.