[nycphp-talk] Active Directory Authentication using LDAP + PHP
keith at keithjr.net
keith at keithjr.net
Tue Feb 24 11:09:25 EST 2004
I noticed someone asking about Active Directory authentication using
straight up php - so I
figured that I would send this along.
This is a snippet of a login script for a calendar scheduling ap that I
wrote in PHP for a
local intranet. You would make a login form, with post variables of
username and password,
and it will authenticate them to the AD server.
How this works: it connects to the LDAP server with a valid login - which
I created the
username ldap in active directory, to query the database, since it would
not allow anonymous
access. You would look up the correct username for that account by
querying the
smaaccountname field for the username that they entered. If that exists,
then get the
correct username to bind to the server with, disconnect, and retry to
connect with the users
proper username and their password. If it connects, you know that it is a
valid username.
I have used this script in their helpdesk application so that passwords
were being checked
vs active directory instead of the internal help desk application's
passwords.
This is just one way of doing it - if anyone else has comments or
questions, please feel
free to let me now!
// connect to LDAP server
$ldap = ldap_connect("172.17.1.11") or die("Cannot connect to the ldap
server :/");
$oudc = "cn=Users, dc=thompsonhealth, dc=org";
$searchdc = "dc=thompsonhealth, dc=org";
$dn2 = "cn=ldap, ".$oudc;
$password = "password";
$auth = false;
//look up OU
if (!($res = ldap_bind($ldap,$dn2,$password)))
{
print(ldap_error($ldap) . "<br>");
die("Could not bind to $dn");
}
else
{
// set search critia for OU
$filter = "samaccountname=".$_POST['username'];
// search OU
$sr = ldap_search($ldap,$searchdc,$filter);
if (!$sr)
{
die("search failed\n");
}
else
{
// get fields from search
$info = ldap_get_entries($ldap,$sr);
if ($info["count"] == 0)
{
$auth = false;
}
else
{
$auth = true;
$user_cn = $info[0]["cn"][0];
}
// disconnect from LDAP server
ldap_unbind($ldap);
}
}
if ($auth == false)
{
die("Could not authenticate you to the Active Directory Server.");
}
$ldap = ldap_connect("172.17.1.11") or die("Cannot connect to AD server :/");
$oudc = "cn=users, dc=thompsonhealth, dc=org";
$dn2 = "cn=".$user_cn.", ".$oudc;
$password = $_POST['password'];
//look up OU
if (!($res = ldap_bind($ldap,$dn2,$password)))
{
$login = 0;
$message = "Invalid Active Directory Password.";
}
else
{
$sr = ldap_search($ldap,"dc=thompsonhealth, dc=org","cn=".$user_cn);
$info = ldap_get_entries($ldap,$sr);
$login = 1;
$message = "You have successfully logged in to Active Directory.<br>
<ul>
<li>Email : ".$info[0]['mail'][0]."</li>
<li>Phone Number : ".$info[0]['telephonenumber'][0]."</li>
</ul>";
}
More information about the talk
mailing list