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.
Related
I am using an Online LDAP Test Server here: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/ to test some basic LDAP code.
I need to authenticate a user and retrieve some user information.
If I understand the information about the test server correctly I should be able to bind with users that belong to respective groups. With the code 'AS IS' below I can bind to un-commented $dn, but if I use any other $dn to authenticate, the bind fails.
What am I not understanding?
For example, tesla should belong to 'ou=scientists,dc=example,dc=com' but I am unable to authenticate tesla on that DN and subsequently I can't search for related information.
$dn = 'dc=example,dc=com';
// $dn = 'ou=mathematicians,dc=example,dc=com';
// $dn = 'ou=scientists,dc=example,dc=com';
$username = 'tesla';
$password = 'password';
$filter = "(uid=" . $username . ")";
$ldapDN = 'uid=' . $username . ',' . $dn;
$ldapCONN = ldap_connect("ldap.forumsys.com") or die("Could not connect to LDAP server.");
if ($ldapCONN)
{
ldap_set_option($ldapCONN, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldapBIND = #ldap_bind($ldapCONN, $ldapDN, $password);
if ( $ldapBIND )
{
$result = ldap_search($ldapCONN, $dn, $filter) or die ("Error: ".ldap_error($ldapCONN));
$data = ldap_get_entries($ldapCONN, $result);
echo '<pre>';
print_r($data);
echo '</pre>';
}
else
{
echo "LDAP bind failed...";
}
}
When using LDAP, it is important to visualize how the database is organized.
Basically, all users are in the main folder. Use this folder to authenticate your user with, otherwise it will not work.
In this case the main folder where all users are in, is dc=example,dc=com. However, most LDAP servers use a main folder like cn=users,dc=example,dc=com.
Why are they using folders at all then? Well, that is to make it easier to categorize and search with a filter. For example, if you want to only show the names of scientists, you add the group Scientists to your search filter like $filter = "(ou=Scientists)". A filter for both groups would look like this: $filter = "(&(ou=Scientists)(ou=Mathematicians)". Now the server will take a look into this folder/these folders, and display just these members.
Hope this helps, for gaining further insight in how the server is organized, I can recommend installing Apache Directory Studio. It is free to download from their site, helped me a lot!
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 know this has sort of been answered before but it hasnt been able to help me (unless it has but because of my limited php knowledge it hasn't helped). Here is my code below:
<body>
<html>
<?php
//echo var_dump($_POST);
$user = "".$_POST["username"]."";
settype($user, "string");
$password = $_POST["password"];
$ldap_host = "ldap.burnside.school.nz";
$base_dn = "ou=students,o=bhs";
$ldap_user = "(cn=".$user.")";
$filter = "($ldap_user)"; // Just results for this user
$ldap_pass = "".$password."";
$connect = ldap_connect($ldap_host)
or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
// This next bit is the important step. Bind, or fail to bind. This tests the username/password.
if (ldap_bind($connect, $ldap_user.",".$base_dn, $ldap_pass)) {
$read = ldap_search($connect, $base_dn, $filter)
or exit(">>Unable to search ldap server<<");
// All the next 8 lines do is get the users first name. Not required
$info = ldap_get_entries($connect, $read);
$ii = 0;
for ($i = 0; $ii < $info[$i]["count"]; $ii++) {
$data = $info[$i][$ii];
if ($data == "givenname") {
$name = $info[$i][$data][0];
}
}
ldap_close($connect);
header("Location: success.php?name=$name");
}
else {
ldap_close($connect);
//header("Location: failure.php?user=$user");
}
?>
</body>
</html>
I am getting an error on line 21 which is when I bind to the server saying:
Warning: ldap_bind(): Unable to bind to server: Invalid DN syntax in S:\XAMPP\htdocs\PhpProject1\LDAP_main.php on line 21
Would anyone have a solution to this problem? It has only started happening when I implemented my $_POST into the code to receive the username and password but as you can see with my commented out // echo var_dump($_POST) I am actually receiving the data I want.
Your DN for binding to the LDAP-Server is (cn=[username]),ou=students,o=bhs which is not a valid DN-Syntax. That should read cn=[username],ou=students,o=bhs without the braces.
You have mixed up an LDAP-Filter (the stuff inside the braces) with a DN.
I'd do an LDAP authentication in the following way:
Bind anonymously or with a default user where you know the DN
Use that user to do a search for all users that match a certain filter that contains the provided username. you can use a filter like (|(mail=[username])(cn=[username])(uid=[username])) to look for entries that have the username in the mail, cn or uid-attribute
Get the DN from the returned Entry (if there are no or more than one entry there is no appropriate user existent so we can skip the rest)
bind to the ldap again with that retreived DN and the provided password.
Have a look at https://gist.github.com/heiglandreas/5689592
how can I authenticate from PHP using LDAP when I only have the SamAccountName and Password? Is there a way to bind with just SamAccountName and Password and without Distinguished Name. The only examples I have found assume you have the DN:
$server="XXX.XXX.XXX.XXX";
$dn = "cn=$username, ";
$basedn="ou=users, ou=accounts, dc=domain, dc=com";
if (!($connect = ldap_connect($server))) {
die ("Could not connect to LDAP server");
}
if (!($bind = ldap_bind($connect, "$dn" . "$basedn", $password))) {
die ("Could not bind to $dn");
}
$sr = ldap_search($connect, $basedn,"$filter");
$info = ldap_get_entries($connect, $sr);
$fullname=$info[0]["displayname"][0];
$fqdn=$info[0]["dn"];
This works for me. I spent many a days trying to figure this one out.
<?php
//We just need six varaiables here
$baseDN = 'CN=Users,DC=domain,DC=local';
$adminDN = "YourAdminDN";//this is the admin distinguishedName
$adminPswd = "YourAdminPass";
$username = 'Username';//this is the user samaccountname
$userpass = 'UserPass';
$ldap_conn = ldap_connect('ldaps://yourADdomain.local');//I'm using LDAPS here
if (! $ldap_conn) {
echo ("<p style='color: red;'>Couldn't connect to LDAP service</p>");
}
else {
echo ("<p style='color: green;'>Connection to LDAP service successful!</p>");
}
//The first step is to bind the administrator so that we can search user info
$ldapBindAdmin = ldap_bind($ldap_conn, $adminDN, $adminPswd);
if ($ldapBindAdmin){
echo ("<p style='color: green;'>Admin binding and authentication successful!!!</p>");
$filter = '(sAMAccountName='.$username.')';
$attributes = array("name", "telephonenumber", "mail", "samaccountname");
$result = ldap_search($ldap_conn, $baseDN, $filter, $attributes);
$entries = ldap_get_entries($ldap_conn, $result);
$userDN = $entries[0]["name"][0];
echo ('<p style="color:green;">I have the user DN: '.$userDN.'</p>');
//Okay, we're in! But now we need bind the user now that we have the user's DN
$ldapBindUser = ldap_bind($ldap_conn, $userDN, $userpass);
if($ldapBindUser){
echo ("<p style='color: green;'>User binding and authentication successful!!!</p>");
ldap_unbind($ldap_conn); // Clean up after ourselves.
} else {
echo ("<p style='color: red;'>There was a problem binding the user to LDAP :(</p>");
}
} else {
echo ("<p style='color: red;'>There was a problem binding the admin to LDAP :(</p>");
}
?>
Actually, the answer is that it depends on how the LDAP server was configured by the admin. You don't always need a DN to authenticate to an LDAP server. In my particular case, even with the DN, I still couldn't authenticate to the LDAP server. For the LDAP server I was trying to connect, it appears it was a Microsoft Domain, and so I could only authenticate with DOMAIN\user015 for user015 in DOMAIN where user015 is a SamAccountName and DOMAIN is the domain for that user. But I was able to authenticate.
Thank you for all the posts! Even if they weren't the correct answer, they did help a lot!
Try user#domain on dn... It worked for me!
You always need a DN to authenticate to a LDAP server. After that, you can perform a filter based in a specific attribute, like SamAccountName, but you need an LDAP user identified by a DN.
The LDAP interface to AD requires that you bind using a DN. In order to authenticate a user, you must first find that user's DN — fortunately, you can find the DN by searching LDAP.
If you configure AD to allow anonymous queries (don't do this unless you are sure you're ok with the reduction in security), you can do
ldap_bind($connect, "", "")
$sr = ldap_search($connect, $base_dn, "(sAMAccountName=$username)")
And then retrieve that user's DN and proceed to rebind with the user's DN and password.
If you do not enable anonymous bind, then you use an application ID to do the initial search, like so:
ldap_bind($connect, "DN=LDAP_App,OU=Users,DC=Domain,DC=com", "thePassword")
$sr = ldap_search($connect, $base_dn, "(sAMAccountName=$username)")
And then, just as above, retrieve that user's DN and proceed to rebind.
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".