cakephp 2.5.7 login->即使密码正确,Auth 始终为 false

cakephp 2.5.7 login->Auth always false even password is correct

我被这个问题困了快一个星期了。即使浏览互联网上的所有解决方案也无法帮助我解决问题。所以我决定在这里问我的问题,希望我能得到解决。

我的问题是为什么我总是得到 Auth FALSE 即使我的密码是正确的?我设法添加了一个新用户并存储了加密的密码,但是当我尝试使用 username 和 `password login 时,它显示“Invalid用户名或密码,重试"

Here is my code.

提前致谢

这部分蛋糕我也遇到了一些麻烦,这是我最终使用的适合我的方法

public function login() {
    if ($this->request->is('post')) {
        $options = array(
            'conditions' => array(
                'User.username' => $this->request->data['User']['username'],
                'User.password' => Security::hash($this->request->data['User']['password'], 'sha256', true)
            ),
            'fields' => array(
                'User.id',
                'User.username',
                'User.group_id',
                // other fields you need
            )
        );

        $userData = $this->User->find('first', $options);
        if (!empty($userData) && $this->Auth->login($userData['User'])) {
            $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Username, and/or password are incorrect'));
        }
    }
}

所以,底线是手动检查具有给定用户名和密码的用户是否存在,然后登录他们。顺便说一句,请注意 login() 函数我正在传递这样的数组

array(
    'id' => 1,
    'email' => 'test@gmail.com',
    'group_id' => 2 
);

而不是

    array(
        'User' => array(
            'id' => 1,
            'email' => 'test@gmail.com',
            'group_id' => 2 
        ) 
    );

此外,如果您使用 cake 2.x,您不想将密码传递给 login 函数,来自 cake 文档 http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted, whereas in 1.3 $this->Auth->login($this->data) would try to identify the user first and only log in when successful.

所以,首先不需要传递密码,但是在使用login之前你应该仔细检查有效的用户密码,因为如果像上面提到的那样,cake会用[=登录用户37=]任意数据.

关于密码散列部分,请确保您使用的散列算法与您在注册​​期间使用的盐完全相同(如果您使用并且应该使用)。

编辑:

尝试在模型的 beforeSave

中使用它
public function beforeSave($options = array()) {
    parent::beforeSave($options);

    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = Security::hash($this->data[$this->alias]['password'], 'sha256', true);
    }
}

对于最后一件事,更好的做法是为每个用户保存一个唯一的盐(盐应该与用户密码一起保存在数据库中)。在 cake 中,只有一个应用程序侧盐被用于所有密码,如果数据库和应用程序被破坏,攻击者可以为所有密码生成一个自定义彩虹 table,但是如果盐对于每个用户都是唯一的,那么坏人应该为每个用户单独创建自定义彩虹 table,这要多得多 work/time/money.