SSO (Single Sign-on) 顾名思义就是几个子项目共用一个登录点. 原理简单来说就是服务端session 共享, 客户端跨域cookies.
实现非常简单,protected/config/main.php中修改session配置即可
代码如下:
1 $host = explode('.', $_SERVER["HTTP_HOST"]); 2 if (count($host) > 2) { 3 define('DOMAIN', $host[1] . '.' . $host[2]); 4 } else { 5 define('DOMAIN', $host[0] . '.' . $host[1]); 6 } 7 8 9 'components' => array( 10 'user' => array( 11 'allowAutoLogin' => true, 12 'autoRenewCookie' => true, 13 // 'class'=>'WebUser', 14 'stateKeyPrefix'=>'xxx', 15 ), 16 'session' => array( 17 'savePath' =>'C:\session_temp', // dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'session_temp', // 'C:\session_temp', // 18 'cookieParams' => array('domain' => '.' . DOMAIN, 'lifetime' => 0), 19 ),
*****
以上代码就是实现代码,Yii配置简单吧,
问题
一. 打开 'class'=>'WebUser', 报错
include(WebUser.php): failed to open stream: No such file or directory
这个是因为没有定义WebUser类, 在protected\components目录下新建WebUser.php,内容如下:
1 <?php 2 3 // this file must be stored in: 4 // protected/components/WebUser.php 5 6 class WebUser extends CWebUser { 7 8 // Store model to not repeat query. 9 private $UserLogin; 10 11 // Return first name. 12 // access it by Yii::app()->user->first_name 13 function getFirst_Name(){ 14 $user = $this->loadUserLogin(Yii::app()->user->user_id); 15 return $user->first_name; 16 } 17 18 // This is a function that checks the field 'role' 19 // in the User model to be equal to 1, that means it's admin 20 // access it by Yii::app()->user->isAdmin() 21 function isAdmin(){ 22 $user = $this->loadUser(Yii::app()->user->user_id); 23 return intval($user->user_role_id) == 1; 24 } 25 26 // Load user model. 27 protected function loadUserLogin($id=null) 28 { 29 if($this->UserLogin===null) 30 { 31 if($id!==null) 32 $this->UserLogin=UserLogin::model()->findByPk($id); 33 } 34 return $this->UserLogin; 35 } 36 }?>
二 . 即使配置好,但子域名还是显示没有登录
这个是因为session保存的位置没有在同一个地方,将savePath改为同一个地方即可
修改前:
1 'savePath' =>dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'session_temp',
修改后:
1 'savePath' =>'C:\session_temp',