我是Cakephp的新手,现在正在我的应用程序中实现LDAP身份验证。官方网站上的"书签"教程中的许多东西都是自动工作的,所以它没有给我足够的信息来了解如何实现一些特定的身份验证。我已经检查了CakePHP3Ldap身份验证问题和澄清,并尝试以这种方式实现我的身份验证,但仍有一些理解问题。
在我的数据库中,我有一个表"Students",它有一个属性"id"作为主键。我的AppController如下所示:
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth', ['authenticate' =>
['Form' =>
['fields' =>
['username' => 'email',
'password' => 'password']
]
], 'loginAction' => [
'controller' => 'Students',
'action' => 'login'
]
]);
$this->Auth->config('authenticate', ['Ldap']);
}
public function isAuthorized()
{
if($this->Auth->user('departmentnumber') == "***") { return true; }
}
LdapAuthenticate类类似于我上面提到的帖子:
namespace App'Auth;
use Cake'Auth'BaseAuthenticate;
use Cake'Network'Request;
use Cake'Network'Response;
class LdapAuthenticate extends BaseAuthenticate {
protected $_host = '***' ;
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 = "cn=Users,dc=***";
$dn = "cn=$username, " . $basedn;
$ldapbind = @ldap_bind($ds, $dn, $password);
if (!$ldapbind) {
return false ;
}
$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) ;
return $user ;
}
}
在StudentsController中,我实现了登录和注销功能,类似于"bookmarker"教程:
public function login(){
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
// user is not identified
$this->Flash->error('Your username or password is not correct');
}
}
public function logout(){
$this->Flash->success('You are now logged out');
return $this->redirect($this->Auth->logout());
}
当我打开任何页面时,我都会成功登录到我的login.ctp页面。在我输入凭据并单击"登录"后,我收到一个错误"SQLSTATE[42S02]:找不到基表或视图:1146表'***_db.users'不存在"。所以我认为我做错了什么,但没有足够的理解来找到哪里——不知道为什么它试图在我的数据库中找到一个不存在的"用户"表。
感谢所有提前帮我提出想法的人!
因为配置不正确。不要在Auth配置中使用Form
,而是使用Ldap
:
$this->loadComponent('Auth', ['authenticate' =>
['Ldap' =>
['fields' =>
['username' => 'email',
'password' => 'password']
]
], 'loginAction' => [
'controller' => 'Students',
'action' => 'login'
]
]);