Friday 20 September 2013

Yii: Single sign on for all subdomains

For example :
Now you have a main domain "mydomain.com" and there are some subdomains such as : id.mydomain.com , news.mydomain.com, blog.mydomain.com ...v.v. So how to with just one log in on "id.mydomain.com" a member can be logged in to the whole system.

It called "Single Sign-on". And we have some way to do it. This document will give you a basic solution with Yii framework.

The requirement:
+ All subdomain running on same server and can be share session.
+ Using same yii session class : CHttpSession or CDbHttpSession

The solution:
We have to configure these website using a same session and a same cookie.

Step 1 : open all main config file which you want to impact.
set a same id for them
array(
            'id' => 'siteID', // change it to same on all subdomain
            'name' => 'site name',
            'defaultController' => 'homepage',
            'theme' => 'web',
            ......
      );

Step 2 : Continue looking on main config files to session array.

* CHttpSession:
if you are using CHttpSession set Cookies params and savePath like this :
'session' => array(
                    'class'=>'CHttpSession',
                   // 'savePath' => dirname(__FILE__).'/../../session',  /*change session path to same folder if not using php default session*/
                    'cookieMode' => 'allow',
                    'cookieParams' => array(
                        'domain' => '.mydomain.com',
                    ),
                ),
CHttpSession save session in file so we just only need to config for all subdomain save session in a same folder. Session folder can be put anywhere but make sure that it is exists and can be access (chmod777).

* CDbHttpSession:
CDbHttpSession is not using savePath param so session array will like that :
'session' => array(
                    'class'=>'CDbHttpSession',
                    'cookieMode' => 'allow',
                    'cookieParams' => array(
                        'domain' => '.mydomain.com',
                    ),
                ),
Session is saved by CDbHttpSession in runtime fordel. we have to config to all application to a same runtime folder. Do it in main config array.
array(
            'id' => 'siteID', // change it to same on all subdomain
            'name' => 'site name',
            'defaultController' => 'homepage',
            'theme' => 'web',
            'runtimePath'=>dirname(__FILE__).'/../../runtime', // change runtime path
            ......
      );

Note : make sure savePath and runtimePath is exists and chmod 777 

Step 3 : Ok, now check your websites.

This is only a basic solution. With a bigger system we have to use more complex technologies such as OAuth 2.0


0 nhận xét:

Post a Comment