CakePHP:仅使用ID登录(不是用户名+密码)

时间:2017-05-21 23:15:20

标签: authentication cakephp login passwords

我是CakePHP和OOP的新手。我在官方网站上关注本教程,该网站教我如何制作博客:https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html

问题是,我希望能够让用户仅使用ID字段登录,而不是使用经典的用户名 - 密码duo。

但我无法找到办法......从我看到的情况来看,Auth Component总是需要两个字段。我该怎么办?我输了。

由于

1 个答案:

答案 0 :(得分:1)

我认为这不是一个好主意,但这样做的方法很简单。

已使用的版本:CakePHP v3.4.5

模板\用户\ login.ctp:

<form method="post" action="<?= $this->Url->build(['controller'=>'Users', 'action' => 'login']) ?>">
    <input type="text" name="id" value="">
    <button type="submit">login</button>
</form>

Controller \ UsersController.php:

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Users->findById($this->request->getData()['id'])->first();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect(['controller' => 'MyController', 'action' => 'MyAction']);
        }
        $this->Flash->error('Id not found.');
        return $this->redirect($this->referer());
    }
}    

不要忘记在AppController中加载AuthComponent并允许非授权用户使用登录方法 - 所描述的内容为here