CakePHP(LDAP)中的备用身份验证源

nic*_*ckf 6 php authentication cakephp ldap

我正在开发一个CakePHP项目,目前正在构建它的用户身份验证部分.问题是我的身份验证信息(即:密码)没有存储在我的数据库中 - 身份验证源是LDAP,但我的问题同样适用于任何非数据库源.

似乎Cake仅在本地数据库中存在时处理密码.蛋糕食谱建议,你可以告诉它不同的控制器/模型/对象通过提供授权程序$this->Auth->authorize变量,但是看代码(具体Auth::startup()功能),它看起来像蛋糕总是试图查询数据库首先,检查获取匹配的用户名/密码,然后查看您指定的备用对象Auth->authorize.也就是说,更改authorize只添加二级过滤器,它不会替换数据库查找.

// The process
1. User provides details
2. Cake checks the database
3. If OK, then check the custom object method
4. If OK, return true

// What I'd like:
1. User provides details.
2. Check the custom object method
3. If OK, return true
4. Profit.
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点的任何想法,希望没有黑客核心文件?

dei*_*zel 8

假设您只是绑定LDAP并从MySQL存储/检索用户数据,这种方法将作为"桥梁"工作,它将自动为成功登录创建帐户:

// app/controllers/components/ldap_auth.php
<?php
App::import('Component', 'Auth');
class LdapAuthComponent extends AuthComponent {
/**
 * Don't hash passwords
 */
    function hashPasswords($data){
        return $data;
    }
/**
 * We will initially identify the user
 */
    function identify($user=null, $conditions=null) {
        // bind credentials against ldap
        $ldapUser = $this->_ldapAuth($user); // do your stuff
        if (!$ldapUser) {
            return null; // if bind fails, then return null (as stated in api)
        }
        // get the cake model you would normally be authenticating against
        $model =& $this->getModel(); // default is User
        // check for existing User in mysql
        $user = $model->find('first', array('conditions' => array(
            'username' => $ldapUser['cn']
        ));
        // if no existing User, create a new User
        if (!$user) {
            $user = $model->save(array('User' => array(
                'username' => $ldapUser['cn'],
                // .. map needed ldap fields to mysql fields ..
            )));
            if (!$user) {
                $this->cakeError('ldapCreateUser');
            }
            // pass the id of the newly created User to Auth's identify
            return parent::identify($model->id, $conditions);
        }
        // pass the id of the existing User to Auth's identify
        return parent::identify($user[$this->userModel][$model->primaryKey], $conditions);
    }
/**
 * Lets check LDAP
 *
 * @return mixed Array of user data from ldap, or false if bind fails
 */
    function _ldapAuth($user) {
        $username = $user[$this->userModel][$this->fields['username']];
        $password = $user[$this->userModel][$this->fields['password']];
        // use the php ldap functions here
        return $ldapUser;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

要使用,替换所有引用到AuthLdapAuth您的应用程序,或按照指示在这里.

请注意,尽管受保护的_ldapAuth()方法可以抽象出LdapUser模型,并且该模型应该从中读取LdapSource,并且LDAP服务器连接设置应该database.php配置中,并且LdapAuthComponent 应该适应使用可配置的字段映射,这些不是要求"完成它".:)