我正在将LDAP身份验证集成到我的项目中。我遵循了CakePHP官方网站上的教程,该教程指导如何在应用程序src路径中创建自定义对象以及如何在AuthController中使用这些自定义对象。
因此,我在src中创建了一个名为Auth的文件夹,文件名为LdapAuthorize.php。路径看起来像这样src / Auth / LdapAuthorize.php
这是我的LdapAuthorize.php代码:
namespace App\Auth;
use Cake\Auth\BaseAuthorize;
use Cake\Network\Request;
class LdapAuthorize extends BaseAuthorize {
public function authorize($user, Request $request) {
if ($user == 'username') { // where username is logged on ldap user on a computer.
return true;
}
}
}
我还在AppController.php文件中调用了该对象。这是我的代码:
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Customers',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
$this->Auth->config('authenticate', [
'Ldap'
]);
}
因此,当我访问URL http://localhost/AppPath/Dashboard/index时,我会得到
Authentication adapter "Ldap" was not found.
由于这是我第一次使用CakePHP,因此在网上找不到太多解决任何问题的解决方案。
为LdapAuthenticate.php添加其他代码:
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
class OpenidAuthenticate extends BaseAuthenticate
{
public function authenticate(Request $request, Response $response)
{
$users = ["john", "ray"];
return $users;
}
}
最佳答案
您需要的是custom authentication adapter,您的LdapAuthorize是custom authorize adapter:
// in src/Auth/LdapAuthenticate.php
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
class LdapAuthenticate extends BaseAuthenticate {
protected $_host = 'your_ldap_server' ;
public function authenticate(Request $request, Response $response) {
$username = $request->data['username'] ;
$password = $request->data['password'] ;
$ds = @ldap_connect($this->_host) ;
if (!$ds) {
throw \Cake\Error\FatalErrorException ('Unable to connect to LDAP host.') ;
}
$basedn = "your ldap query... "
$dn = "uid=$username, ".$basedn;
$ldapbind = @ldap_bind($ds, $dn, $password);
if (!$ldapbind) {
return false ;
}
// Do whatever you want with your LDAP connection...
$entry = ldap_first_entry ($ldapbind) ;
$attrs = ldap_get_attributes ($ldapbind, $entry) ;
$user = [] ;
// Loop
for ($i = 0 ; $i < $attrs["count"] ; $i++) {
$user[$attrs[$i]] = ldap_values ($ldapbind, $entry, $attrs[$i])[0] ;
}
// Then close it and return the authenticated user
ldap_unbind ($ldapbind) ;
ldap_close ($ldapbind);
return $user ;
}
}