CakePHP keep session from main domain across to a subdomain

authentication, cakephp, session

Solution

Sessions (CakePHP 2.x):

To make the session cookie valid for all your subdomains and the top level domain, you actually need to set it yourself in your `APP/config/bootstrap.php` file:

ini_set('session.cookie_domain', '.domain.com');

Then, in your `APP/config/core.php` file, set Security to low:

Configure::write('Security.level', 'low');

"otherwise the referer_check will be set to the current HTTP_HOST in the CakeSession object line 441."

Sessions (CakePHP 3.x)

The session cookie path defaults to app’s base path. To change this you can use the session.cookie_path ini value. For example if you want your session to persist across all subdomains you can do:

Configure::write('Session', [
    'defaults' => 'php',
    'ini' => [
        'session.cookie_path' => '/',
        'session.cookie_domain' => '.yourdomain.com'
    ]
]);

Cookies (CakePHP 2.x):

On this page it explains that you can use the 'domain' variable:

The domain name allowed to access the cookie. e.g. Use ‘.yourdomain.com’ to allow access from all your subdomains.

Per their example code:

<?php
public $components = array('Cookie');
public function beforeFilter() {
    parent::beforeFilter();
    $this->Cookie->name = 'baker_id';
    $this->Cookie->time =  3600;  // or '1 hour'
    $this->Cookie->path = '/bakers/preferences/';
    $this->Cookie->domain = 'example.com';
    $this->Cookie->secure = true;  // i.e. only sent if using secure HTTPS
    $this->Cookie->key = 'qSI232qs*&sXOw!';
    $this->Cookie->httpOnly = true;
}

Cookies (CakePHP 3.x):

Read here.

The domain that the cookie is available. To make the cookie available on all subdomains of example.com set domain to ‘.example.com’.

Problem

I am working with Cakephp and I have an issue maintaining session across subdomains. My problem is as follows: - Users login on 'localhost/login' - If authenticated they are redirected to 'customer.localhost/home'. Currently Cake is creating a cookie for each domain ie localhost and customer.localhost. This means that I cannot keep the session working for the user. Is there a way to make all cookies domain fixed to the parent domain with the goal of keeping the session working across subdomains? I have tried entering this in my bootstrap but it has no effect: ini_set('session.cookie_domain', '.localhost'); If you think this cannot be done please feel free to let me know so that I can move on from this frustrating problem. Many thanks, kSeudo

Original source