Active Directory integration with Wordpress and LDAP - php

I am implementing Wordpress authentication with Active Directory Credentials using LDAP. For this I have dedicated service account ‘user’. With this service account I am not able to getting complete user list which is required for authentication purpose. I am not sure but It could be the case of permissions with service account.
I am able to connect with AD with the service account but when I am trying to query for users, it returns nothing. I need whole user list from AD
// config
$ldapserver = 'My server';
$ldapport = 389;
$ldapuser = 'User';
$ldappass = 'password';
$ldaptree = "complete String";
// connect
$ldapconn = ldap_connect($ldapserver,$ldapport) or die("Could not connect to LDAP server.");if($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...<br /><br />";
$filter = "(&(&(&(objectCategory=person)(objectClass=user))))";
$result = ldap_search($ldapconn,$ldaptree, $filter) or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
// SHOW ALL DATA
echo '<h1>Dump all data</h1><pre>';
print_r($data);
echo '</pre>';
// iterate over array and print data for each entry
echo '<h1>Show me the users</h1>';
for ($i=0; $i<$data["count"]; $i++) {
//echo "dn is: ". $data[$i]["dn"] ."<br />";
echo "User: ". $data[$i]["cn"][0] ."<br />";
if(isset($data[$i]["mail"][0])) {
echo "Email: ". $data[$i]["mail"][0] ."<br /><br />";
} else {
echo "Email: None<br /><br />";
}
}
// print number of entries found
echo "Number of entries found: " . ldap_count_entries($ldapconn, $result);
} else {
echo "LDAP bind failed...";
}}// all done? clean up
ldap_close($ldapconn);

Here is a guide / code snippit for authenticating using PHP and active directory. If you are dead set on retrieving ALL users for some reason simply modify the filter, and then remove the break statement in the for loop.
http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/

Related

Place check on Active Directory user fields using PHP

I am creating a user in Active Directory using PHP and create it correctly, but now I need to check the options shown in the image from the same PHP code, I also attach an example of how the user created in Active Directory using PHP.
Checks that I need to do using PHP
User creation code
<?php
// Username used to connect to the server
$username = "administrator";
// Password of the user.
$password = "Password01";
// Domain used to connect to.
$domain = "nagara.ca";
// Proper username to connect with.
$domain_username = "$username" . "#" . $domain;
// User directory. Such as all users are placed in
// the Users directory by default.
$user_dir = "OU=Students,DC=nagara,DC=ca";
// Either an IP or a domain.
$ldap_server = "192.168.100.2";
// Get a connection
$ldap_conn = ldap_connect($ldap_server);
// Set LDAP_OPT_PROTOCOL_VERSION to 3
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("Could not set LDAP Protocol version");
// Authenticate the user and link the resource_id with
// the authentication.
if($ldapbind = ldap_bind($ldap_conn, $domain_username, $password) == true)
{
// Setup the data that will be used to create the user
// This is in the form of a multi-dimensional
// array that will be passed to AD to insert.
$adduserAD["cn"] = "testuser";
$adduserAD["givenname"] = "Test";
$adduserAD["sn"] = "User";
$adduserAD["sAMAccountName"] = "testuser";
$adduserAD['userPrincipalName'] = "testuser#nagara.ca";
$adduserAD["objectClass"] = "user";
$adduserAD["displayname"] = "Test User";
$adduserAD["userPassword"] = "Password01";
$adduserAD["userAccountControl"] = "544";
$base_dn = "cn=testuser,ou=students,DC=nagara,DC=ca";
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true)
{
// The user is added and should be ready to be logged
// in to the domain.
echo "User added!<br>";
}else{
// This error message will be displayed if the user
// was not able to be added to the AD structure.
echo "Sorry, the user was not added.<br>Error Number: ";
echo ldap_errno($ldap_conn) . "<br />Error Description: ";
echo ldap_error($ldap_conn) . "<br />";
}
}else{
echo "Could not bind to the server. Check the username/password.<br />";
echo "Server Response:"
// Error number.
. "<br />Error Number: " . ldap_errno($ldap_conn)
// Error description.
. "<br />Description: " . ldap_error($ldap_conn);
}
// Always make sure you close the server after
// your script is finished.
ldap_close($ldap_conn);
?>
I hope you can support me.
Thank you very much.

login PHP to Active Directory Fail

I am trying to verify the authentication of a user through a simple PHP code but I always get the same error "Invalid credentials ".
$ldap_dn = "uid=".$_POST["username"].",DC=xxx,DC=xxx,DC=xxx,DC=xxx,DC=xxx";
$ldap_password = $_POST["password"];
$ldap_con = ldap_connect("xxx", 389);
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION,3);
//check connection
if ($ldap_con === FALSE) {
die("<p> Couldn't connect to LDAP service </p>");
} else {
echo "<p> connessione avvenuta con successo </p>";
}
// check authentication
if(#ldap_bind($ldap_con, $ldap_dn, $ldap_password)){
echo "Autenticato";
}else{
echo "Autenticazione Fallita <br>";
echo ldap_error($ldap_con);
}
PHP code runs on XAMP on a PC W7pro already logged into the company domain.
I have obtained the AD address from the same machine on which I perform the tests; for retrive DN I've used the program "Softerra LDAP browser", but actually I'm not sure for this parameter.
When a user logs on to the domain, the username uses three letters of the surname followed by two of the name, e.g. Name = Alfred / Surname = Pecora username = pecal.
Does $ldap_dn in your code match the DN in AD properly?
If you are administrator for the AD, you can confirm it by executing dsquery command on DOS prompt on the AD.
e.g.,
dsquery user -name pecal
Or you can use the format <name>#<domain> instead of DN format:
$ldap_dn = $_POST["username"]."#example.com";
I ran a new test:
$adServer = "xxx";
$ldap = ldap_connect($adServer,389);
$username = $_POST['username'];
$password = $_POST['password'];
$ldapRdnLogin = "CN=MyName MySurname,OU=CED,OU=Users,DC=intranet,DC=xxx,DC=xxx,DC=xx,DC=it";
$ldapRdn = "OU=Users,DC=intranet,DC=xxx,DC=xxx,DC=xx,DC=it";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = #ldap_bind($ldap, $ldapRdnLogin, $password);
if ($bind) {
$filter="(sAMAccountName=$username)";
$result = ldap_search($ldap,$ldapRdn,$filter);
ldap_sort($ldap,$result,"sn");
$info = ldap_get_entries($ldap, $result);
for ($i=0; $i<$info["count"]; $i++)
{
if($info['count'] > 1)
break;
echo "<p>You are accessing <strong> ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."</strong><br /> (" . $info[$i]["samaccountname"][0] .")</p>\n";
echo '<pre>';
var_dump($info);
echo '</pre>';
$userDn = $info[$i]["distinguishedname"][0];
}
#ldap_close($ldap);
} else {
$msg = ldap_error($ldap);
echo $msg;
}
In the above example the binding "MyName MySurname" \ DN works and I can perform the search.
I think that the problem is to find the right DN to bind with sAMAccountName

PHP ldap_get_entries() return count=zero

I am trying to authenticate users' login against LDAP(Server is Mac El Capitan).
I can successfully connect and bind to the ldap server.
I can search and sort the result.
But when I perform "ldap_get_entries",I received "Zero" entry.
I've tried everything from StackOverFlow to Google's second page.
Any Suggestions or idea why this might be happening?
MY CODE -
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$usernameLogin=$_POST['email'];
$passwordLogin=$_POST['password'];
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
echo "User name is ".$username;
echo "</br>";
$ldapUser = "uid=xxxxxx,cn=users,dc=dns1,dc=xxxxxxxx,dc=com";
$ldapPass = "xxxxxxxxxxx";
$url = "ldap://dns1.xxxxxxx.com:389";
$ldap = ldap_connect("$url") or die("Could not connect to LDAP server.");
$baseDN = "cn=users,dc=dns1,dc=xxxxxxxxx,dc=com";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS,0);
$bind = ldap_bind($ldap, $ldapUser, $ldapPass);
if($bind) {
echo "Connected To LDAP";
echo "</br>";
$filter="(sAMAccountName=$username)";
echo "Filter = ".$filter;
echo "</br>";
$result = ldap_search($ldap,$baseDN,$filter) or die("Could not search.");
echo "Result = ".$result;
echo "</br>";
$sort = ldap_sort($ldap,$result,"uid");
echo "Sort = ".$sort;
echo "</br>";
$number = ldap_count_entries($ldap, $result);
echo "Count Entries = ".$number;
echo "</br>";
$info = ldap_get_entries($ldap, $result);
echo "Data for " . $info["count"] . " items returned:<p>";
echo "Info = ".$info;
echo "</br>";
echo '<pre>'; print_r($info); echo '</pre>';
echo "</br>";
$fentry= ldap_first_entry($ldap, $result);
echo "First Entry = ".$fentry;
for ($i=0; $i<$info["count"]; $i++)
{
if($info['count'] > 1)
break;
echo "<p>You are accessing <strong> ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."</strong><br /> (" . $info[$i]["samaccountname"][0] .")</p>\n";
echo '<pre>';
var_dump($info);
echo '</pre>';
$userDn = $info[$i]["distinguishedname"][0];
}
ldap_close($ldap);
}
else{
echo "Cannot Connect To LDAP.";
}
}}
?>
I can connect - bind - search But "ldap_get_entries()" returns zero.
First: You can skip the or die "Could not connect to LDAP Server" as that will almost never happen. ldap_connect only checks the parameter for syntactical correctness and does not actually connect to the server. The actual connection happens on the first call to the server which usually is ldap_bind. That's why conncetion issues often surface on ldap_bind and not on ldap_connect.
Second: Where did you get samAccountName from? That's a field that's usually used by ActiveDirectory. In Apples OpenDirectory the user is usually identified by the uid-attribute. So your filter should be sprintf('uid=%s', $username).
Third: I doubt that only Users in the group "Open Directory Administrators" are allowed to bind agains the LDAP. They for sure are the only ones allowed to edit the directory but every other user can bind as well.
Fourth: ldap_sort is deprecated by now. It's not sorting on the server side but on the client side. So only the returned results are sorted. When you have paged results that means that - even though you sorted the result - there still will be entries that would fit right in between your results. I'm currently working on a way to use server-sided sorting but that relies on the feature to be available on the server. So you can use ldap_sort but you can also implement your own sorting on the result set.
So change the filter to uid=$username and you'll get the expected results. The mail attribute might also contain the full email-address and might therefore then fail! You can also adapt the filter to search more than one field. Have a look at this slide for short examples.
Solved it. I used "mail" instead of "sAMAccountName".
Here's the details -
1 ) From
$filter="(sAMAccountName=$username)";
to
$filter="(mail=$username)";
2 ) From
$sort = ldap_sort($ldap,$result,"uid");
to
$sort = ldap_sort($ldap,$result,"mail");
That's it.
Lessons learn from here -
Use "LDAP Admin Tool" or some sort of LDAP Tool to understand the structure of your LDAP environment before jumping into coding. Big lesson learnt.

Issue authenticating with LDAP

I'm trying to use IP.Board LDAP Login Handler; however, although the server connects and the query I perform is correct, I'm unable to login with a LDAP account. It throws the common "unknown username" error. The script connects successfully, because if I use wrong credentials it throws an authentication error in the LDAP settings page; this also happens if I force a ldap_search(): Search: Bad search filter or a ldap_search(): Search: Operations error when messing with the settings and trying to log in with an account in the Login Page. So the problem I believe should be somewhere else...
To test the settings I'm using, I have performed a successfully connection with the following code:
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);
// config
$ldapserver = 'server ip';
$ldapuser = 'username';
$ldappass = 'password';
$ldaptree = "OU=The,DC=path,DC=to,DC=users";
// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");
if($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...<br /><br />";
$result = ldap_search($ldapconn,$ldaptree, "(cn=*)") or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
// SHOW ALL DATA
echo '<h1>Dump all data</h1><pre>';
print_r($data);
echo '</pre>';
// iterate over array and print data for each entry
echo '<h1>Show me the users</h1>';
for ($i=0; $i<$data["count"]; $i++) {
//echo "dn is: ". $data[$i]["dn"] ."<br />";
echo "User: ". $data[$i]["cn"][0] ."<br />";
if(isset($data[$i]["mail"][0])) {
echo "Email: ". $data[$i]["mail"][0] ."<br /><br />";
} else {
echo "Email: None<br /><br />";
}
}
// print number of entries found
echo "Number of entries found: " . ldap_count_entries($ldapconn, $result);
} else {
echo "LDAP bind failed...";
}
}
// all done? clean up
ldap_close($ldapconn);
?>
It renders the array completely, showing me the complete list of users belonging to that path and that should be enough for IPB to validate the information, isn't it?
Since the connection is actually successful but it doesn't locate an user, it doesn't generate any Log record about it.
I already checked the LDAP username's permissions exposed in this thread: https://serverfault.com/questions/167371/what-permissions-are-required-for-enumerating-users-groups-in-active-directory/167401 so the user has administrative rights and also can read those elements.
This is quite frustrating. Any advise?
I found the UID field required by IPB was CNin our LDAP setup. After correcting this small thing, I finally managed to perform the sync

Ldap get dynamic values via PHP

so i had used php to connect to AD using LDAP and i had successfully retrieved the data using LDAP-PHP connection...
my ad is like...
my code is...
<?php
// config
$ldapserver = 'ad.univ3.edu';
$ldapuser = 'some';
$ldappass = 'some';
$ldaptree1 = "OU=TEST,OU=STUDENT,DC=ad,DC=univ3,DC=edu";
// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
if($ldapconn){
echo "Connected to ".$ldapserver.'<br /><br />';
}
if($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...<br /><br />";
$result = ldap_search($ldapconn, $ldaptree1, "cn=*") or die ("Error in search query: ".ldap_error($ldapconn));
$data = ldap_get_entries($ldapconn, $result);
//SHOW ALL DATA
echo '<pre>';
print_r($data);
echo '</pre>';
$count = ldap_count_entries($ldapconn, $result);
// print number of entries found
echo "Number of entries found: " . $count;
} else {
echo "LDAP bind failed...";
}
}
// all done? clean up
ldap_close($ldapconn);
?>
i got details in print_r($data); but i get it in array...
i need like.. find all OU inside domain dynamically and get count in each OU(like users, computers, etc...) via specifying only domain..
i don't want to hardcode stuff like..
$ldaptree1 = "OU=TEST,OU=STUDENT,DC=ad,DC=univ3,DC=edu";
any ideas?? i can't get reference to do this as the information about LDAP is Generic...
Thanks in advance...

Categories