Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

naderghazi's avatar

Use sanctum stateful authentication for different domains

In my new project, I need to create an authentication system, the requirements are:

  1. authentication should be done for different domains and sub-domains
  2. for now, the only client type is front-end applications(SPA)
  3. site A can have two domains, company.my-domain.com and a custom domain for itself like: company.com

the first thing that came to my mind was to use stateless authentication by JWT tokens, but I couldn't think of a way to securely store JWT in the front-end, storage is vulnerable to XSS, and CSRF for cookies should be considered. laravel sanctum stateless authentication is not using the cookies and sessions, that's why I don't think for this app stateless authentication is a good choice.

the second way and stateful way was to use the cookies, which is supported by sanctum by default, but the problem is I cannot use cookies for different domains, so I have to point different domains to my server and create virtual hosts, so that :

  • company.my-domain.com sends its requests to the api.my-domain.com (cause cookies can be shared between subdomains)
  • company.com sends its requests to the api.company.com (cause api.my-domain.com cannot set cookies for another domain)

the problem is, laravel is using an environment variable called SESSION_DOMAIN, and you can only set it once, I can't and don't want to launch a new instance with different env variables for each custom domain, so my question is:

how to set the session domain environment variables dynamically? and does the fact that I'm using octane will affect other requests in this case? because I used Config::set(), it does affect the X-CSRF-TOKEN but not any of the sanctum cookie domains

any help and recommendation would be appreciated!

0 likes
2 replies
martinbean's avatar

@naderghazi You can’t. Sanctum uses cookies for stateful authentication and a cookie issued on site-a.com cannot be read and used on entirely different top-level domain like site-b.com.

2 likes
naderghazi's avatar

@martinbean Thanks for your answer, I'm not trying to do it, as I said, I want to make custom domains send their requests to the api.custom-domain.com and set DNS record for custom-domain.com to send their requests to my server, and in there, I can decide to send different domain requests to my instance of application by virtual host.

Please or to participate in this conversation.