首页 > 解决方案 > CakePHP Auth->identify() 返回 false

问题描述

我正在玩 CakePHP,但似乎无法登录。似乎 $this->Auth->identify() 不断返回 false 并且不允许我登录。

我已经阅读了有关我的问题的所有以前的帖子,但是,没有人为我提供解决方案。我尝试登录的用户都是使用 cake 密码哈希创建的,我检查过该密码已存储在数据库中。我检查了数据库中设置为 varchar (255) 的密码字段长度,我检查了 Auth => authenticate => Form => 字段设置为正确的值(login.ctp 字段也是正确的)。我还尝试按照某人的建议将 $this->Form->control() 更改为 $this->Form->input() ,但没有运气。

应用控制器:

 $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'classes'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'index'
            ]
  ]);
$this->loadComponent('Auth', [
                'authenticate' => [
                    'Form' => [
                        'fields' => [
                            'username' => 'email',
                            'password' => 'password'
                        ]
                    ]
                ],
                'loginAction' => [
                    'controller' => 'Users',
                    'action' => 'login'
                ]
        ]);

UsersController 中的 login() 函数:

public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            pj($user);
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect(['controller' => 'users']);
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

登录.ctp:

<div class="users form">
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->input('email') ?>
        <?= $this->Form->input('password') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>

编辑:我忘了补充说我可以成功添加用户,我只是无法登录。

标签: cakephpcakephp-3.0

解决方案


您在 AppController 中加载 AuthComponent 两次。未加载带有表单字段配置的第二次加载。

使用所需的配置一次加载组件。

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'fields' => [
                'username' => 'email',
                'password' => 'password'
            ]
        ]
    ],
    'loginRedirect' => [
        'controller' => 'Users',
        'action' => 'classes'
    ],
    'logoutRedirect' => [
        'controller' => 'Users',
        'action' => 'index'
    ],
    'loginAction' => [
        'controller' => 'Users',
        'action' => 'login'
    ]
]);

推荐阅读