2016-10-04 280 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建议你认为我应该使用哪些代码。 –

相关问题