从MD5 Legacy Auth系统转换为CakePHP

时间:2013-07-04 20:10:57

标签: php security cakephp authentication user-experience

我有一个网站,它运行密码的MD5哈希方案。作为支持这个遗留系统的一种方式,我this回答了现在手动覆盖登录系统的问题。但这并不是很理想,因为MD5在加密方面几乎被普遍认为是非常糟糕的。因此,为了安全起见,将用户迁移到更安全的CakePHP身份验证系统而不会造成过度悲痛的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

感谢this answer(虽然经过轻微修改)。基本上,如果当前系统与之不匹配,它会在幕后更新用户以使用新系统。

/**
 *  Login method
 */
public function login() {
    $this->layout = 'homepage';
    // If the user is already logged in, redirect to their user page
    if($this->Auth->user() != null) {
        $this->redirect();
    } else {
        // If this is being POSTed, check for login information
        if($this->request->is('post')) {
            if($this->Auth->login($this->loginHelper($this->request->data))) {
                // Redirect to origin path, ideally

            } else {
                $this->Session->setFlash('Invalid username or password, try again');
            }
        }           
    }
}

/**
 *  Update password method
 *  @param array The user's data array
 *  @param Returns either a user object if the user is valid or null otherwise
 */
private function loginHelper($data) {
    $username = $this->data['User']['username'];
    $plainText = $this->data['User']['password'];

    $user = current($this->User->findByUsername($username));

    $salted = Security::hash($plainText, null, true);

    if ($salted === $user['password']) {
        return $user; // user exists, password is correct
    }

    $md5ed = Security::hash($plainText, 'md5', null);

    if ($md5ed === $user['password']) {
                $this->User->id = $user['id'];
        $this->User->saveField('password', $plainText);

        return $user; // user exists, password now updated to blowfish
    }

    return null; // user's password does not exist.
}