0

你好吗?我试图弄清楚为什么这不起作用...查看互联网,最常见的答案是我的数据库的密码字段大小错误,但我的是varchar(255).

继续获得false回报$user = $this->Auth->identify();

我的代码:

应用控制器:

[...]
public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');

    $this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authError' => 'Para continuar, você precisa logar.',
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ]
    ]);

    $this->loadComponent('Security');
}

用户控制器:

[...]

use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;

[...]

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();

        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Usuário ou senha ínvalido, tente novamente'));
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

用户(模型实体):

[...]

protected $_hidden = [
    'password',
];

protected function _setPassword($password)
{
    return (new DefaultPasswordHasher)->hash($password);
}

看法:

<?= $this->Form->create('User', ['url' => ['controller' => 'Users', 'action' => 'login']]) ?>
    <div class="form-group">
        <label for="email">
            <?= $this->Form->control('email', ['class' => 'form-control']) ?>
        </label>
    </div>
    <div class="form-group">
        <label for="password">
            <?= $this->Form->control('password', ['class' => 'form-control']) ?>
        </label>
    </div>
    <div class="form-group">
        <?= $this->Form->submit('Login', ['class' => 'btn btn-info btn-md']) ?>
    </div>
<?= $this->Flash->render() ?>
<?= $this->Form->end() ?>
4

1 回答 1

0

Finnaly 弄清楚发生了什么: 奇怪的是,我对密码进行了两次哈希处理...... add() 方法中有这行代码:

$hasher = new DefaultPasswordHasher();
$user['password'] = $hasher->hash($user['password']);

所以......删除它后,一切都很顺利。感谢您的所有回复!

于 2020-06-11T21:23:47.750 回答