2013-02-09 41 views
0

我需要在YII應用程序的所有頁面上強制進行身份驗證。要做到這一點,我已經延長了SiteController類用下面的代碼,我從http://www.heirbaut.nl/2010/02/23/forcing-a-yii-application-to-authenticate/有:爲什麼Yii強制認證只能在主頁/靜態頁面上工作?

/** 
* @return array action filters 
*/ 
public function filters(){ 
    return array(
     'accessControl', // perform access control for CRUD operations 
    ); 
} 

/** 
* Specifies the access control rules. 
* This method is used by the 'accessControl' filter. 
* @return array access control rules 
*/ 
public function accessRules(){ 
    return array(
     array('allow', // allow all users to perform 'login' 
      'actions'=>array('login'), 
      'users'=>array('*'), 
     ), 
     array('allow', // allow authenticated user to perform any action 
      'users'=>array('@'), 
     ), 
     array('deny', // deny all users 
      'users'=>array('*'), 
     ), 
    ); 
} 

這隻做什麼它應該,重定向unauthenticaed用戶的所有請求登錄表單,對於index.php URL。但是index.php?r=person和因此,應用程序的主菜單繞過這個限制,並顯示出來,無論任何保證。

+2

待辦事項你有一個'PersonController'? – topher 2013-02-09 07:49:29

+0

是的。每個控制器是否需要引用相同的代碼?如果你說的確如此,當然不適宜創建一個新的類來繼承。但是這看起來好像很多鍋爐板代碼。我能不能解決這個問題在Yii上鍊更高? – aelgoa 2013-02-09 08:12:11

回答

0

每個控制器都需要引用該代碼。一種選擇是創建自己的控制器,擴展CController並將其放置在你的protected/components文件夾

class MyController extends CController{ 
    /** 
    * @return array action filters 
    */ 
    public function filters(){ 
     return array(
      'accessControl', // perform access control for CRUD operations 
     ); 
    } 

    /** 
    * Specifies the access control rules. 
    * This method is used by the 'accessControl' filter. 
    * @return array access control rules 
    */ 
    public function accessRules(){ 
     return array(
      array('allow', // allow authenticated user to perform any action 
       'users'=>array('@'), 
      ), 
      array('deny', // deny all users 
       'users'=>array('*'), 
      ), 
     ); 
    } 
} 

然後在您需要擴展MyController並覆蓋accessRules()添加任何額外的規則你的控制器類

public class SiteController extends MyController{ 

    ... 

    public function accessRules(){ 
     $rules=parent::accessRules(); 
     array_unshift($rules,array(
      'allow', // allow all users to perform 'login' 
      'actions'=>array('login'), 
      'users'=>array('*'), 
     )); 
     return $rules; 
    } 

    ... 
} 
+0

謝謝,這證實了我的假設,並且效果很棒! – aelgoa 2013-02-09 11:46:14