CakePHP 2:覆盖AuthComponent的"密码"方法

Nic*_*ick 10 authentication passwords cakephp

我的目标是为每个用户提供一个独特的盐,而不是仅仅Configure::read('Security.salt')为每个用户使用.

我知道CakePHP 2.x不再自动散列密码.这允许我对密码执行模型验证,这是非常好的.但是,我没有看到我可以覆盖AuthComponent的"密码"方法的方法.因此,即使我可以控制密码在保存到数据库之前如何进行哈希处理,但我无法控制在执行实际登录时如何对密码进行哈希处理.从食谱:

在调用之前,您不需要哈希密码 $this->Auth->login().

如何$this->Auth->login()使用自定义密码哈希方法?

谢谢.

更新:我最终选择了Hannibal Lecter博士的答案(创建自定义身份验证对象).这是怎么做的:

旧代码:

$this->Auth->authenticate = array('Form' => array('fields' => array('username' => 'email')));
Run Code Online (Sandbox Code Playgroud)

新代码(将"表单"更改为"自定义"):

$this->Auth->authenticate = array('Custom' => array('fields' => array('username' => 'email')));
Run Code Online (Sandbox Code Playgroud)

创建"app/Controller/Component/Auth/CustomAuthenticate.php"并使其如下所示:

<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');

class CustomAuthenticate extends FormAuthenticate {
}
Run Code Online (Sandbox Code Playgroud)

从"lib/Cake/Controller/Component/Auth/BaseAuthenticate.php"复制"_findUser"和"_password"方法,并将它们粘贴到"CustomAuthenticate"类中.然后对"_findUser"方法进行以下两个修改:

  1. 从"$ conditions"数组中删除此行: $model . '.' . $fields['password'] => $this->_password($password),

  2. 更改if (empty($result) || empty($result[$model])) {if (empty($result) || empty($result[$model]) || $result[$model][$fields['password']] != $this->_password($password, $result[$model]['id'])) {

然后对"_password"方法进行以下两个修改:

  1. 通过更改protected function _password($password) {为创建"$ id"参数protected function _password($password, $id) {

  2. 通过更改return Security::hash($password, null, true);为更新salt值return Security::hash($password, null, Configure::read('Security.salt') . $id);

最后,AuthComponent::password使用Security::hash与上述相同的逻辑更新要使用的所有事件.

dr *_*ter 4

您可能可以创建一个自定义身份验证对象并根据您的喜好对密码进行哈希处理。查看现有的 auth 对象以了解它们的工作原理。