Skip to content

Instantly share code, notes, and snippets.

@anhtuank7c
Created April 9, 2016 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anhtuank7c/116e1f491ae1773675be59754c0948cb to your computer and use it in GitHub Desktop.
Save anhtuank7c/116e1f491ae1773675be59754c0948cb to your computer and use it in GitHub Desktop.
LDAP authentication
<?php
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
class LdapAuthenticate extends BaseAuthenticate
{
protected $_host = 'your_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=your_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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment