Monday, April 28, 2008

PHP and LDAP

The joys of authentication. So, now I am working on running some of our PHP apps to authenticate against Active Directory (AD). Well, my limited knowledge in AD is telling me that it shouldn't be too hard. After all, AD is just a Microsoft interface to LDAP. Right?

Well, it turns out that, yeah, from a PHP perspective, it is. It is actually pretty easy, once you are comfortable with working with an LDAP structure.

So, here is the basics of it. I have a simple page that all it does is print out the results of a simple authentication to an AD server:
<html>
<body> 
<h1>AD Test</h1>
<?php
// Variables to use with ldap_bind
$ldapuser  = 'username@some.domain.com';     // ldap username with suffix
$ldappasswd = 'notmyrealpw';  // associated password

// connect to AD server
$adconn = ldap_connect("ad_controler.myco.com")
or die("Could not connect to LDAP server.");

// if a connection was made attempt a binding
if ($adconn) {

// bind to ldap
$ldapbind = ldap_bind($ldapconn, $ldapuser , $ldappass);  

// Check authentication
if ($ldapbind) {
echo "User is authenticated.";
} else {
echo "User was not authenticated.";
}

// unbind the connection
ldap_unbind($adconn);
}
?>
</body>
</html>


Basically, you have your username, for example avgwebgeek. Then you have a suffix, which is your account suffix for your domain, for example "@myco.com". Put them together (along with a password) and you have your AD authentication information. Of course, the username and password would be sent through request parameters. Granted, this is a pretty simplistic view of AD authentication. You can do a whole lot more, like searching, and updating AD information. I learned all about it by looking through the adLDAP Project. The hard part was realizing that I didn't have PHP enabled on my server. Hint: if you get a message like "Call to undefined function: ldap_connect() ", that means that your LDAP isn't enabled for PHP. The adLDAP page has a FAQ that explains that as well.

No comments: