The code below gets me the ldap username and full name...I am a little new to LDAP so I was wondering how may I also get the user phone number?
What is it that I need to add to my code to make it echo out the phone number as well?
<?php
$x=1;
if($x==1)
{
//LDAP stuff here.
$username = "stuff";
$password = "stuffhere";
echo("Authenticating...");
$ds = ldap_connect('ldap host');
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
//Can't connect to LDAP.
if( !ds )
{
echo "Error in contacting the LDAP server -- contact ";
echo "technical services! (Debug 1)";
exit;
}
//Connection made -- bind anonymously and get dn for username.
$bind = #ldap_bind($ds);
//Check to make sure we're bound.
if( !bind )
{
echo "Anonymous bind to LDAP FAILED. Contact Tech Services! (Debug 2)";
exit;
}
$search = ldap_search($ds, "rdn here", "uid=$username");
//Make sure only ONE result was returned -- if not, they might've thrown a * into the username. Bad user!
if( ldap_count_entries($ds,$search) != 1 )
{
echo "Error processing username -- please try to login again. (Debug 3)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
$info = ldap_get_entries($ds, $search);
//Now, try to rebind with their full dn and password.
$bind = #ldap_bind($ds, $info[0][dn], $password);
if( !$bind || !isset($bind))
{
echo "Login failed -- please try again. (Debug 4)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
//Now verify the previous search using their credentials.
$search = ldap_search($ds, "rdn here", "uid=$username");
$info = ldap_get_entries($ds, $search);
if( $username == $info[0][uid][0] )
{
echo $username;
echo $info[0][cn][0];
exit;
}
else
{
echo "Error. Access Denied";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
ldap_close($ds);
exit;
}
?>
RFC4519 gives telephoneNumber as the attribute for a phone number in the standard user schema. List this attribute in the requested attributes list in the search request. For more information about query a directory server, see "LDAP: Using ldapsearch" and "LDAP: Programming Practices".
Related
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
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.
I want to change a LDAP directory user's password using PHP.
After I bind to LDAP, I look for the desired user's dn with the samaccount name and retrieve the dn:
$filter="(samaccountname=desiredname.desiredname)";
$result = ldap_search($lh, $personnel_base, $filter) or die(ldap_error($lh));
//$data = ldap_get_entries($lh, $result);
$entry = ldap_first_entry($lh, $result);
$atribute = ldap_get_attributes($lh, $entry);
Then I use ldap_mode_replace to change the password:
$newpass = "Cevadetest123#!";
ldap_mod_replace($lh, $dn, array('userpassword' => "{MD5}".base64_encode(pack("H*",md5($newpass) ) ) ) ) or die(ldap_error($lh));
echo "Password changed!";
Though I get Password changed! output, the password remains unchanged.
Any suggestions?
EDIT: I just noticed that the attribute userpassword does change, but to login via LDAP I have to use the OLD password! What soccerry is this?
I found the answer. First of all, the field I had to change was unicodePwd, which cannot be read - it can only be modified. In order to write to this field you must firstly have a secure connection to LDAP. The hostname therefore is: ldaps://hostname.something.local
The next important step is to encrypt the password before writing the field:
$newpassword="HelloWorld123";
$newpassword = "\"".$newpassword."\"";
$newPass = mb_convert_encoding($newpassword, 'UTF_16LE')
You can find the complete code here.
I'll just paste it below in case something happens with the link:
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
$ldapconn = ldap_connect('ldaps://127.0.0.1', 636);
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
$ldapuser="ldapuser";
$ldappwd="*****";
// search for user
ldap_bind($ldapconn, "CN=$ldapuser,CN=Users,DC=my,DC=company,DC=example", $ldappwd);
$res_id = ldap_search( $ldapconn, "CN=Users,DC=my,DC=company,DC=example", "sAMAccountName=$username");
if ($res_id) {
$entry_id = ldap_first_entry($ldapconn, $res_id);
if($entry_id){
$user_dn = ldap_get_dn($ldapconn, $entry_id);
if ($user_dn) {
$ldapbind = ldap_bind($ldapconn, $user_dn, $oldpassword);
// check if the old password allows a successfull login
if($ldapbind) {
if(strcmp($newpassword, $newpassword2)==0){
// create the unicode password
$newpassword = "\"" . $newpassword . "\"";
$newPass = mb_convert_encoding($newpassword, "UTF-16LE");
//rebind as admin to change the password
ldap_bind($ldapconn, "CN=$ldapuser,CN=Users,DC=my,DC=company,DC=example", $ldappwd);
$pwdarr = array('unicodePwd' => $newPass);
if(ldap_mod_replace ($ldapconn, $user_dn, $pwdarr)) {
print "<p class='success'>Change password succeded.</p>\n";
} else {
print "<p class='error'>Change password failed.</p>\n";
}
}else{
print "<p class='error'>New password must be entered the same way twice.</p>\n";
}
}else{
print "<p class='error'>Wrong user name or password.</p>\n";
}
} else {
print "<p class='error'>Couldn't load user data.</p>\n";
}
} else {
print "<p class='error'>Couldn't find user data.</p>\n";
}
} else {
print "<p class='error'>Username was not found.</p>\n";
}
if(ldap_error($ldapconn)!="Success"){
print "<p class='error'>LDAP Error:<br />\n";
var_dump(ldap_error($ldapconn));
print "</p>\n";
}
#ldap_close($ldapconn);
I'm trying to implement some code from these pages but unsuccessfully.
I need to do ldap authentication from php and have this code:
<?php
$ldap['user'] = "tester";
$ldap['pass'] = "test";
$ldap['host'] = '147.32.99.8';
$ldap['port'] = 636;
$ldap['conn'] = ldap_connect( $ldap['host'], $ldap['port'] )
or die("Could not conenct to {$ldap['host']}" );
$ldap['bind'] = ldap_bind($ldap['conn'], $ldap['user'], $ldap['pass']);
if( !$ldap['bind'] )
{
echo ldap_error( $ldap['conn'] );
exit;
}
echo "<p>";
echo ($ldap['bind'])? "Valid Login" : "Login Failed";
echo "</p><br />";
ldap_close( $ldap['conn'] );
?>
But it doesn't work. I'm almost sure that in user name is missing domain. But where can I find domain? I have only IP address.
From Softera ldap browser I have following informations:
URL: ldaps://147.32.99.8:636/cn=tester,ou=staff,ou=uceeb,o=cvut
Maybe there is another mistake not only missing domain but I'm really LDAP beginner.
Thank you for any reply that will help me.
This code sometimes works:
function authUserAD($username, $password, $ldap_server="147.32.99.8") {
$auth_user = $username;
if($connect = ldap_connect($ldap_server)){
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
if(ldap_bind($connect, $auth_user, $password)) {
ldap_close($connect);
return(true);
}
}
ldap_close($connect);
return(false);
}
if(authUserAD("cn=tester,ou=staff,ou=uceeb,o=cvut", "test")) echo "<p>Login/password OK.</p>";
else echo "<p>Connection error.</p>";
But in LDAP administration I have to change the value of Require TLS for simple links with password to NO and after that again back to YES. After this two operations it works. But how to do it without this strange operation.
I am wanting to create a form that I can fill out and once I submit it the form values can be pulled out and that person can be created into LDAP. I am not very experienced with LDAP infact I just worked towards making an LDAP bind work so I am needing some help. How can I add new users into LDAP through this form I can fill out? I know LDAP has an Add commands but I am not particularly sure on how to get started and what information needs to be passed for the person to be created in LDAP. If it helps, below is my code for LDAP bind.
<?php
$name=$_REQUEST['name'];
$x=1;
if($x==1)
{
//LDAP stuff here.
$username = "myusername";
$password = "mypass";
$ds = ldap_connect('ldap://ldap:389');
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
//Can't connect to LDAP.
if( !ds )
{
echo "Error in contacting the LDAP server -- contact ";
echo "technical services! (Debug 1)";
exit;
}
//Connection made -- bind anonymously and get dn for username.
$bind = #ldap_bind($ds);
//Check to make sure we're bound.
if( !bind )
{
echo "Anonymous bind to LDAP FAILED. Contact Tech Services! (Debug 2)";
exit;
}
$search = ldap_search($ds, "ou=People,DC=sde,DC=goliat,DC=com", "uid=$username");
//Make sure only ONE result was returned -- if not, they might've thrown a * into the username. Bad user!
if( ldap_count_entries($ds,$search) != 1 )
{
echo "Error processing username -- please try to login again. (Debug 3)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
$info = ldap_get_entries($ds, $search);
//Now, try to rebind with their full dn and password.
$bind = #ldap_bind($ds, $info[0][dn], $password);
if( !$bind || !isset($bind))
{
echo "Login failed -- please try again. (Debug 4)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
//Now verify the previous search using their credentials.
$search = ldap_search($ds, "ou=People,DC=sde,DC=goliat,DC=com", "cn=$name");
$info = ldap_get_entries($ds, $search);
if( $username == "myusername" )
{
/*
very useful set of information to view the LDAP tree info from an array
echo $username;
echo "<pre>".print_r($info[0],true)."</pre><br />";
*/
echo $info[0][cn][0];
echo ",";
echo $info[0][mail][0];
echo ",";
echo $info[0][telephonenumber][0];
exit;
}
else
{
echo "Error. Access Denied";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
ldap_close($ds);
exit;
}
?>
I would recommend a newUser.php (or whatever) file that checks to make sure that all of your required information is present, then send that info to the file you have started above.
Your $bind should take three variables...
$bind = ldap_bind($ds, 'cn=root,dc=example,dc=com', secretPassword);
For a pretty good guide to adding people to your LDAP server via PHP go to http://www.php2python.com/wiki/function.ldap-add/
Good luck
An add request requires the distinguished name to be added and the attribute that are to be part of the entry, and optional request controls.
On another subject, your search has subtree scope and may return more than one entry that matches user name. There is no reason why there could not be multiple entries with the same RDN in different branches underneath the base object specified in the code - unless your directory server vendor has implemented an attribute uniqueness constraint.