yii2 Cookies Cross-subdomain authentication and identity cookies


Example

In case of autologin or "remember me" cookie, the same quirks as in case of subdomain cookies are applying. But this time you need to configure user component, setting identityCookie array to desired cookie config.

Open you application config file and add identityCookie parameters to user component configuration:

$config = [
    // ...
    'components' => [
        // ...
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
            'loginUrl' => '/user/login',
            'identityCookie' => [ // <---- here!
                'name' => '_identity',
                'httpOnly' => true,
                'domain' => '.example.com',
            ],
        ],
        'request' => [
            'cookieValidationKey' => 'your_validation_key'
        ],
        'session' => [
            'cookieParams' => [
                'domain' => '.example.com',
                'httpOnly' => true,
            ],
        ],

    ],
];

Note that cookieValidationKey should be the same for all sub-domains.

Note that you have to configure the session::cookieParams property to have the samedomain as your user::identityCookie to ensure the login and logout work for all subdomains. This behavior is better explained on the next section.