CakePHP 3 Auth 在用户以外的模型上

CakePHP 3 Auth on model other than User

我正在使用 CakePHP 重建项目,并遵循此处的新身份验证文档: http://book.cakephp.org/3.0/en/controllers/components/authentication.html

根据我的阅读,Cake3 默认使用 userModel='User',但它可以选择将其设置为您想要的任何值。就我而言,我在 'Account' 模型中拥有所有身份验证数据(即 userModel => 'Account')。

因此,在我的帐户实体中,我添加了以下代码:

protected function _setPassword($password)
{
    return (new DefaultPasswordHasher)->hash($password);
}

此外,在我的帐户 table 中,我的 'passwd' 字段设置为 varchar(255) [我读过出于某种原因需要这样做]。

当我使用默认烘焙 'add' 和 'edit' 方法时,密码以纯文本形式存储,而不是散列。我发现解决这个问题的唯一方法是在 AccountsTable class 中创建一个自定义方法,然后使用这个 kludge 调用它:

$this->request->data['passwd'] = $this->Accounts->hashPassword($this->request->data['passwd']);

我的 Auth 组件看起来像这样...

$this->loadComponent('Auth', [
        'loginAction' => [
            'controller' => 'Accounts',
            'action' => 'login'
        ],
        'authError' => 'Unauthorized Access',
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'username',
                    'password' => 'passwd'
                ],
                'userModel'=>'Accounts'
            ]
        ]
    ]);

有没有办法不用处理原始请求数据就可以做到这一点?

您的修改器命名错误,修改器的约定是 _set 后跟驼峰式 field/property 名称。因此,由于您的字段名称是 passwd,而不是 password,因此必须将其命名为 _setPasswd

protected function _setPasswd($password)
{
    return (new DefaultPasswordHasher)->hash($password);
}

另见 Cookbook > Entities > Accessors & Mutators