cakephp 2.5.7 login-> Auth总是假,即使密码是正确的

时间:2015-01-16 03:38:35

标签: cakephp authentication

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

我的问题是为什么我总是得到验证 FALSE,即使我的密码是正确的?我设法添加新用户并存储加密密码,但当我尝试使用username和`密码登录时,会显示" 无效的用户名或密码,再试一次"

Here is my code

提前感谢

1 个答案:

答案 0 :(得分:0)

我对这部分蛋糕也有一些麻烦,这是我最终使用的方式对我有用

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 docs http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

  

在2.x $ this-> Auth->登录($ this-> request-> data)会将用户登录   无论发布什么数据,而在1.3中   $ this-> Auth-> login($ this-> data)将首先尝试识别用户   并且只在成功时登录。

所以,首先不需要传递密码,但在使用login之前应该小心检查有效的用户密码,因为如上所述,cake将使用任意一个登录用户数据

关于密码哈希部分,请确保您使用的是与注册期间使用的完全相同的盐(如果您使用的话)相同的哈希算法。

修改

尝试在模型的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);
    }
}

最后一件事是更好的做法是为每个用户保存一个唯一的盐(盐应该与用户的密码一起保存在db中)。在蛋糕中,只有一个应用程序端盐用于所有密码,如果数据库和应用程序受到攻击,攻击者只能为所有密码生成一个自定义彩虹表,但如果每个用户的盐都是唯一的,那么坏人应该为每个用户单独创建自定义彩虹表,这是更多的工作/时间/金钱。