2013-10-11 36 views
3

我是CakePHP的新手。我試着用CakePHP 2.4.1來嘗試the Cake cookbook tutorial of simple authentication
雖然我輸入了正確的用戶名和密碼,但我總是收到「用戶名或密碼無效,請重試」。CakePHP簡單認證教程不起作用

public function login() { 
    if ($this->request->is('post')) { 
     if ($this->Auth->login()) { 
      return $this->redirect($this->Auth->redirect()); 
     } 
     $this->Session->setFlash(__('Invalid username or password, try again')); 
    } 
} 

根據the AuthComponent API,如果參數到Auth->login()是空的或沒有指定,則該請求將被用來識別用戶。 調試查詢輸出顯示

SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified` 
FROM `cake_dvdcatalog`.`users` AS `User` WHERE `User`.`username` = 'admin' LIMIT 1 

這裏是我的用戶模型:

// app/Model/User.php 
App::uses('AuthComponent', 'Controller/Component'); 

class User extends AppModel { 

    public $validate = array(
     'username' => array(
      'required' => array(
       'rule' => array('notEmpty'), 
       'message' => 'A username is required' 
      ) 
     ), 
     'password' => array(
      'required' => array(
       'rule' => array('notEmpty'), 
       'message' => 'A password is required' 
      ) 
     ), 
     'role' => array(
      'valid' => array(
       'rule' => array('inList', array('admin', 'author')), 
       'message' => 'Please enter a valid role', 
       'allowEmpty' => false 
      ) 
     ) 
    ); 

    public function beforeSave($options = array()) { 
     if (isset($this->data[$this->alias]['password'])) { 
      $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); 
     } 
     return true; 
    } 
} 
+0

您可以發佈您的用戶模型代碼嗎? – Andrew

+0

@安德魯,當然。我編輯了我的問題。 – Sithu

+0

嘗試調試$ this-> Auth-> login()方法。加密的密碼應該與數據庫中的相同。 – Dezigo

回答

0

中的驗證組件出現在控制器不是模型。嘗試從模型中刪除此:

App::uses('AuthComponent', 'Controller/Component');

並將其添加到該AppController的。此外它添加到應用程序控制器:

public $components = array('Auth');

你可能需要一些額外的配置,如果你想使用非默認設置。

+0

根據食譜教程,'$ components = array('Auth');'已經在'AppController'中定義。 – Sithu

+0

您需要1)確保實際的AppController文件包含組件。 2)上面的原始帖子顯示你正在加載用戶模型中的auth組件,這是不正確的。組件對應於控制器,而不是模型。 –

+0

Cookbook教程本身顯示,Auth組件在用戶模型和AppController中都被加載。無論如何,我將它從模型中刪除。 – Sithu

1

你必須檢查你的加密密碼, CakePHP的默認使用SHA1,所以這是尤爲明顯,以創建使用CakePHP與SHA1密碼的用戶,添加beforesave方法在用戶模式加密密碼

0

檢查你在'AppController.php'文件的$ components數組中有以下項目:

'authenticate' => array(
    'Form' => array(
     'passwordHasher' => 'Blowfish' 
    ) 
)