5

我正在從CakePHP 1.3遷移到CakePHP 2.2.2並希望對簡單管理區域使用基本Http身份驗證。我只是無法使其工作,我認爲我在文檔中理解錯誤。CakePHP 2基本身份驗證驗證

從文檔我明白我必須做一些像

public $components = array(
    'Auth' => array(
     'authenticate' => array(
     'Basic' 
    ), 
     'authError' => 'You may not access this area.', 
     'authorize' => array('Controller') 
    ) 
); 

據我所知,還我需要延長BaseAuthenticate組件返回有效用戶的日期,但即使有上述的配置我會想到的是,瀏覽器的Http Access對話框將在一個彈出窗口中打開。但是沒有發生這種情況,而是我被重定向到/ users /不存在的登錄名。爲什麼我需要Http Access的登錄視圖?我很困惑。

回答

7

Auth組件添加到您的控制器(或到AppController

class ThingsController extends AppController { 
    var $components = array('Auth'); 
} 

CakePHP的需要登錄動作,所以即使你使用基本身份驗證,該HTTP代理負責用戶界面要收集驗證細節,您需要在某個控制器中指定一個操作來處​​理登錄(在基本情況下,如果用戶尚未驗證,它將發送WWW-Authenticate: Basic標題)。

您可以設置AuthCompoment$loginAction,但這個默認值(和建議不打破慣例)在UsersControllerlogin方法。因此,首先在View/Users/login.ctp創建一個空的模板,然後將以下添加到您的UsersController

class UsersController extends AppController { 

    public $components = array(
     'Session', 
     'Auth' => array(
      'authenticate' => array('Basic') 
     ) 
    ); 

    public function login() { 
     if ($this->Auth->login()) { 
      return $this->redirect($this->Auth->redirect()); 
     } else { 
      $this->Session->setFlash('Not able to login'); 
     } 
    } 

    public function logout() { 
     $this->redirect($this->Auth->logout()); 
    } 

} 
+0

謝謝你,成功了! –