我正在从事 CakePHP 项目,目前正在构建其中的用户身份验证部分。问题是我的身份验证信息(即:密码)没有存储在我的数据库中——身份验证源是 LDAP,但我的问题同样适用于任何非数据库源。
看起来好像 Cake 只处理本地数据库中存在的密码。 The Cake Cookbook suggests您可以使用 $this->Auth->authorize
变量告诉它一个不同的 Controller /模型/对象来提供授权过程,但是查看代码(特别是 the Auth::startup()
function )它看起来像 Cake 一样,总是会首先 尝试查询数据库,检查匹配的用户名/密码,然后再查看您使用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.
关于如何做到这一点的任何想法,希望不会破解核心文件?
最佳答案
假设您只是简单地绑定(bind) 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;
}
}
?>
要使用,请在您的应用程序中将所有对 Auth
的引用替换为 LdapAuth
或遵循 instructions here .
请注意,尽管 protected _ldapAuth()
方法可以 抽象为LdapUser
模型,并且该模型应该 从 LdapSource
读取,LDAP 服务器连接设置应该在 database.php
配置中,LdapAuthComponent
应该 适应使用可配置的字段映射,这些不是“完成它”的要求。 :)
关于php - CakePHP (LDAP) 中的替代身份验证源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1397091/