【问题标题】:CakePHP 3 Auth on model other than User用户以外的模型上的 CakePHP 3 Auth
【发布时间】:2015-04-27 15:28:48
【问题描述】:

我正在使用 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);
}

此外,在我的帐户表中,我的“passwd”字段设置为 varchar(255) [我已阅读出于某种原因需要该字段]。

当我使用默认的“添加”和“编辑”方法时,密码以纯文本形式存储,而不是散列。我发现解决这个问题的唯一方法是在 AccountsTable 类中创建一个自定义方法,然后使用这个 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'
            ]
        ]
    ]);

有没有一种方法可以做到这一点,而无需使用原始请求数据?

【问题讨论】:

  • 跟进 AccountsTable->hashPassword 与 Accounts->_setPassword() 函数完全相同。
  • 谢谢@user4838338。从你的问题中得到了我的答案

标签: cakephp-3.0


【解决方案1】:

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

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

另请参阅Cookbook > Entities > Accessors & Mutators

【讨论】:

  • 谢谢!我知道我在那里遗漏了一些明显的东西。
  • 我这里也有同样的问题,但是它说“SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Users.username' in 'where Clause'”
  • @Daroath 这是个问题吗?无论如何,这与 OP 遇到的问题相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2018-07-20
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多