2016-10-04 307 views
0

我試圖按照所有規定的方式在CakePHP3中實現登錄功能。除了官方Cake網站的Authentication頁面上的主要方法之外,我已經嘗試了很多方法。用戶登錄操作無效,在CakePHP3中顯示無效的用戶名和密碼

我收到的錯誤是「無效的用戶名或密碼」。下面是我用過的代碼快照。請注意,我遵循了CakePHP的正確命名約定,因此不存在配置問題。此外,問題是3.x版本,所以請不要回答舊版本。

文件:UsersController>登陸行動

public function login() { 
    if($this->Auth->user()){ 
     $this->Flash->error(__('You are already logged in!')); 
      return $this->redirect($this->Auth->redirectUrl()); 
    } 
    if ($this->request->is('post')) { 
     $user = $this->Auth->identify(); 
     if ($user) { 
      $this->Auth->setUser($user); 
      $this->Flash->success(__('You\'re successfully logged-in.')); 
      return $this->redirect($this->Auth->redirectUrl()); 
     } 
     $this->Flash->error(__('Username or password is incorrect')); 
    } 
} 

文件:AppController的>初始化功能

public function initialize() 
{ 
    parent::initialize(); 
    $this->loadComponent('Flash'); 
    $this->loadComponent('Auth', [ 
     'loginAction' => [ 
      'controller' => 'Users', 
      'action' => 'login', 
     ], 
     'authError' => 'Did you really think you are allowed to see that?', 
     'authenticate' => [ 
      'Form' => [ 
       'fields' => ['username' => 'username'] 
      ] 
     ], 
     'storage' => 'Session' 
    ]); 
    $this->Auth->allow(['display']); 
    $this->Auth->allow(['register']); 
} 

文件:登錄查看

<?php 
echo $this->Form->create(); 
    echo $this->Form->input('username'); 
    echo $this->Form->input('password'); 
    echo $this->Form->button('Login', ['class' => 'btn']); 
echo $this->Form->end(); 
?> 

希望,我沒有錯過任何東西,但它仍然沒有按預期工作。 任何建議將不勝感激。

TIA

回答

1

它不是在沒有PasswordHasher的Auth組件中工作。 您應該將其添加到/src/Model/Entity/User.php

在末尾添加以下代碼。另外添加使用Cake \ Auth \ DefaultPasswordHasher;

protected function _setPassword($value){ 
     $hasher = new DefaultPasswordHasher(); 
     return $hasher->hash($value); 
    } 

添加新用戶後,嘗試用它登錄。

+0

是的。這是工作正常,但現在我無法使用以下代碼檢查登錄狀態: if($ this-> Auth-> user()){ $ this-> Flash-> error(__('You are已經登錄!')); return $ this-> redirect($ this-> Auth-> redirectUrl()); } –

+0

老兄,不理我以前的評論。其實,我試圖在AppController中使用這個(登錄狀態檢查)代碼,而我應該在UsersController中使用它。 謝謝! –

+0

是否有任何錯誤?調試模式必須打開。 –

0

是在文件src /型號/實體/ user.php的使用DefaultPasswordHasher用戶實體? 只是一個想法...

+0

不,但我猜這不是必需的,除非我不使用PasswordHasher加密密碼。不過,我也很樂意嘗試這一點。 Plz建議你認爲我應該使用哪些代碼。 –

相關問題