So I’ve been working on a portal that authenticates via LDAP and then forwards to a page and uses sessions for all of this. I’ve hacked together a lot of code I have found from all over the internet and have finally got it working… almost. I am a total newbie with php so if someone could help me with this I’d be grateful…
The main issue is that it is using the display name in AD to check the inputed user name against (I think?). If I try to login with my example ad account, inv_bind, which has its display name also set to inv_bind, authentication works correctly. However if I change its display name at all, authentication fails. Same issue on any other account. If displayname matches the login name, everything works fine. The full code is near the bottom, but the next part is what I’m pretty sure is wrong. I just don’t know how to fix it.
Something in this is telling it to get the display name?
The offending part:
if($bind = @ldap_bind($ldap, $user, $password)) {
// valid
// check presence in groups
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$filter = "(samAccountName=" . $user . ")";
$attr = array("memberof");
$result = ldap_search($ldap, $LDAP_DN, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
ldap_unbind($ldap);
Full code:
error_reporting(0);
function authenticate($user, $password) {
// Active Directory server
$ldap_host = "test.local";
// Active Directory DN
$LDAP_DN = 'OU=Users,OU=Computer Operations,OU=Departments,OU=Corporate,DC=test,DC=local';
// Active Directory user group
$ldap_user_group = "inv_read";
// Active Directory manager group
$ldap_manager_group = "inv_write";
// connect to active directory
$ldap = ldap_connect($ldap_host);
// verify user and password
if($bind = @ldap_bind($ldap, $user, $password)) {
// valid
// check presence in groups
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$filter = "(samAccountName=" . $user . ")";
$attr = array("memberof");
$result = ldap_search($ldap, $LDAP_DN, $filter, $attr) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap, $result);
ldap_unbind($ldap);
// check groups
foreach($entries[0]['memberof'] as $grps) {
// is manager, break loop
if (strpos($grps, $ldap_manager_group)) { $access = 2; break; }
// is user
if (strpos($grps, $ldap_user_group)) $access = 1;
}
if ($access != 0) {
// establish session variables
$_SESSION['user'] = $user;
$_SESSION['access'] = $access;
return true;
} else {
// user has no rights
return false;
}
} else {
// invalid name or password
return false;
}
}