【发布时间】:2016-01-15 16:01:13
【问题描述】:
UsersController.php 的登录动作 =>
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}
我创建了一个用户。 添加 UsersController.php 的操作 =>
public function add()
{
$this->set('groups', $this->Users->Groups->find('list'));
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$article = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($article)) {
$this->Flash->success(__('New user has been saved.'));
return $this->redirect(['controller' => 'posts', 'action' => 'index']);
}
$this->Flash->error(__('Unable to add new user.'));
}
}
用户实体 =>
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity
{
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
AppController.php 中的授权配置 =>
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Posts',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Posts',
'action' => 'index'
]
]);
$this->Auth->allow();
}
login.ctp =>
<h2>Login</h2>
<?php
echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' =>'login')));
echo $this->Form->input('User.username',array('style'=>'width:50%'));
echo $this->Form->input('User.password',array('style'=>'width:50%'));
echo $this->Form->submit('Login');
echo $this->Form->end();
?>
$this->request->data 返回这些=>
[
'User' => [
'username' => 'user2',
'password' => 'userpassword'
]
]
数据库用户表中保存的密码格式为:$2y$10$ZP9WngYH74tdlOfBKpix2ORfvs/NN2.WIstWpg7qgGpoSwDhaMU8q
为什么我无法登录?为什么 $this->Auth->identify();总是返回 false?
我们将不胜感激。
提前致谢。
【问题讨论】:
-
请包含您的 AuthComponent 配置。
-
是的,请确保您的 AppController AuthComponent 设置正确。
-
您确实错过了 AppController 中的 AuthComponent 配置,至少还有 login.ctp。
-
@DavidYell,我已经编辑了提供身份验证组件配置的原始问题。
-
@hmic,我已经编辑了提供 login.ctp 的原始问题。
标签: php cakephp login cakephp-3.0