Skip to content
Advertisement

Laravel : Set cookie for parent domain

I’m trying to build an SSO that will be shared between different applications with the same parent domain. Say we have these domains :

sso.example.com Unified login page

app1.example.com Some other application that will redirect to the login page

When I set SESSION_DOMAIN=.example.com in .env file of the SSO project, the cookie is indeed set in parent domain and is accessible from the APP1. However, the app will also set the other cookies such XSRF-TOKEN. I don’t want to mess with parent domain cookies since there’s also another independant app that uses that domain.

I tried to change the session.domain property on the fly of every request and change it back right after but it’s not working. I guess the cookie is set when the response is finished which is not the case

Config::set('session.domain','.domain.com');
Cookie::queue('ssotoken', 'test', 60);
Config::set('session.domain','sso.domain.com');

So any workaround to set only the “ssotoken” for parent domain ? Or is there a way to access sso.example.com cookies from app1.example.com in Laravel ?

Advertisement

Answer

You can set the cookie domain for a specific cookie at their fifth parameter, like this:

Cookie::queue(
    name: 'ssotoken',
    value: 'test',
    domain: '.domain.com'
);

Without named parameters your method call looks like this:

Cookie::queue('ssotoken', 'test', 0, null, '.domain.com')

It’s a bit hard to see because Cookie::queue doesn’t have any documented parameters since they’re using the array spread operator, to either accept an already invoked Cookie class or allow to build a cookie without the setp of nesting two methods. The parameters supplied in the example correspond with those documented in the Cookie::make method:

Cookie::make(
    string $name,
    string $value,
    int $minutes = 0,
    string|null $path = null,
    string|null $domain = null,
    bool|null $secure = null,
    bool $httpOnly = true,
    bool $raw = false,
    string|null $sameSite = null
)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement