Cakephp 3.1,为什么$ this-> Auth-> identify();总是回归虚假?

时间:2016-01-15 16:01:13

标签: php cakephp login cakephp-3.0

UsersController.php =>

的登录操作
SnapToDevicePixels

我创建了一个用户。 添加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'
            ]);
        }
    }
}

用户实体=>

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.'));
        }
    }

AppController.php中的身份验证配置=>

<?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);
        }
    }
}

login.ctp =&gt;

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();   
}

<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(); ?> 会返回这些=&gt;

$this->request->data

以这种格式保存在数据库用户表中的密码:[ 'User' => [ 'username' => 'user2', 'password' => 'userpassword' ] ]

为什么我无法登录?为什么$ this-&gt; Auth-&gt; identify();总是返回假?

任何帮助都将受到高度赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:3)

您需要在Auth配置中添加要检查的字段,如:

'Form' => [
  'fields' => [
    'username' => 'username',
    'password' => 'password'
  ]
]

此外,您的表单错误,需要读取如下内容,从控制器传递实体。

$this->Form->create($userEntity);

不要在字段前加上(错误的)模型,只需使用:

$this->Form->input('username');
$this->Form->input('password');