This had me stumped for a while so I figured it would be nice to share here to avoid others the grief.
The Yii application is divided into several subdomains, or each subdomain has its own Yii application.
A user should be able to log in to any subdomain and be logged in to another subdomain and the root domain.
Actually rather simple through the use of cookies.
First thing is to set the user, session and cookie parameters properly in the main configuration file (only pertinent sections are shown) :
'components' => array( 'user' => array( // enable cookie-based authentication 'allowAutoLogin' => true, ), // session configuration 'session' => array( 'savePath' => '/some/writeable/path', 'cookieMode' => 'allow', 'cookieParams' => array( 'path' => '/', 'domain' => '.yourdomain.com', 'httpOnly' => true, ), ),
Explanation:
The 'savePath' should be set the same across all Yii applications that share the session.
Notice the '.' in front of the cookie domain name, this is what tells the cookie to span multiple subdomains, so 'yourdomain.com', 'a.yourdomain.com' and 'b.yourdoamin.com' will be matched.
The cookie's 'path' parameter is set to '/', this means the cookie will be valid for all paths.
Next, and this is the crucial bit with Yii (the above cookie configuration is generic PHP), the Yii application ID must be set in the config file:
array( 'id' => 'yourdomain',
Explanation:
Finally, the user cookie parameters must also be set to be identical as in the configuration file :
class MyWebUser extends CWebUser { public $identityCookie = array( 'path' => '/', 'domain' => '.yourdomain.com', ); ...
Or you can grab the settings from the configuration settings. This is especially useful when the settings will change, for example to set different domain names and/or paths for local, pre-production and production environments.
class MyWebUser extends CWebUser { public function init() { $conf = Yii::app()->session->cookieParams; $this->identityCookie = array( 'path' => $conf['path'], 'domain' => $conf['domain'], ); parent::init(); }
That's it !!! This setup has been tested pretty thouroughly, but please provide comments/suggestions below on improving this article.
Total 6 comments
how to deal with CSRF cookies?
it is working if I check "remember me next time" and doesn't authenticate if I don't. In other words working with cookies and not with sessions. It does create session file but doesn't save details. More about this issue is http://www.yiiframework.com/forum/index.php/topic/38535-single-sign-on-sso-with-yii-user-rights/
can you help please?
Where should we put the MyWebUser class file? you did not explain about it.
I would say, don't forget to clear your cookies while testing this thing.
It should make no difference what type of session storage you are using. I have used file based and MySQL storage no problem.
can't we use this with CDbHttpSession?
Leave a comment
Please login to leave your comment.