身份验证登录在 cakephp 中不起作用


Auth login doesn't work in cakephp

>我写了一个用户控制器,如果提交的用户名和passwort(用cakephp的安全性加密::hash()=>,它应该登录用户,例如 6b0deec0d563224524da45691584643bc78c96ea,没有其他哈希设置)匹配数据库中的行。但它不起作用,我不知道为什么。

这是我的用户控制器的一个片段.php

public function add() {
    $this->set("title_for_layout", "Register");
    if($this->request->is("post")) {
        $this->User->set($this->request->data);
    if($this->User->save(array("password" => Security::hash($this->request->data["User"]["password"])))) {
            $this->Session->setFlash(__("Successfully registred."), "flash_success");
            $this->redirect("/login");
    } else {
        $this->Session->setFlash(__("Validation failed."), "flash_danger");
    }
    }
}

注册工作正常,并在数据库中创建了一行,其中我有包含普通用户名的列"用户名",例如"myuser"和包含散列字符串的"密码"。我认为这个问题不能在这里解决。

这是我的用户控制器的另一个片段.php

public function login() {
    $this->set("title_for_layout", "Login");
    if($this->request->is("post")) {
        if($this->Auth->login()) {
            $this->Session->setFlash("Login successfull.", "flash_success");
        } else {
            $this->Session->setFlash("Login failed.", "flash_danger");
        }
    }
}

这是视图登录.ctp

<?php echo $this->Form->create('User'); ?>
<?= $this->Form->input("username"); ?>
<?= $this->Form->password("password"); ?>
<?= $this->Form->end("submit"); ?>

这是我的问题:登录总是失败。此外,我在$component数组中没有任何设置。

如何解决问题?

如果你使用的是 cakePHP 2.x,那么你可以在模型的回调函数中将密码加密设置为

<?php
// app/Model/User.php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
// ...
public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}
?>

有关更多信息,请点击链接。如果您仍然想在控制器中加密密码,那么您可以使用类似的代码。

public function add() {
    $this->set("title_for_layout", "Register");
    if($this->request->is("post")) {
        $this->User->set($this->request->data);
    if($this->User->save(array("password" => $this->Auth->password($this->request->data["User"]["password"])))) {
            $this->Session->setFlash(__("Successfully registred."), "flash_success");
            $this->redirect("/login");
    } else {
        $this->Session->setFlash(__("Validation failed."), "flash_danger");
    }
    }
}
?>

如果您使用的是 cakePHP 2.4 或更高版本,请按照此处的文档进行操作。