Posts tagged ‘PHP’

Active Directory intergration with PHP

You have an Active Directory and an intranet/extranet, but want to tie them together onto the same username/password system? It couldn’t be easier, using PHP’s LDAP Extension.

In case you didn’t already know, Microsoft’s Active Directory uses the LDAP protocol to store and communicate it’s data. As this is an open protocol, there’s plenty you can integrate it with. In this article, I’ll focus on PHP.

It’s really easy to get started integrating PHP with LDAP. There’s many truly great and in depth articles on this subject, such as one from Developer.com. If you want long explanations, head they way. Over here, I’ve got a quick and dirty example:

<?php

$username = "administrator";
$password = "MYSecur3Password4";
$server = "192.168.10.5";

$connect = ldap_connect($server);
$bind = ldap_bind($connect, $username, $password);

if($bind == TRUE) {
echo "LDAP Connect Success!";
} else {
echo "LDAP Connect Failure!";
}

?>

That will do a really simple connect to your Active Directory server, such as a Microsoft Windows Server 2008. You can modify this code to grab the username and password as user input from a login form, and then authenticate against that.

However, you must always check to make sure the username and password fields are not empty, or else it will probably authenticate anonymously and return a TRUE value. Here’s a modified example to grab the data from a logon form as POST data:

<?php

if(empty($_POST['username']) || empty($_POST['password'])) {
die("Username or Password field was left blank. Please try again.");
}

$username = $_POST['username'];
$password = $_POST['username'];
$server = "192.168.10.5";

$connect = ldap_connect($server);
$bind = ldap_bind($connect, $username, $password);

if($bind == TRUE) {
echo "LDAP Connect Success!";
} else {
echo "LDAP Connect Failure!";
}

?>

So, that’s the basics. However, it’s probably not much good if you want to do anything else than a quick authentication check. The PHP LDAP Extension supports a myriad of fancy things, from searching to editing and even deleting records. But you don’t want to do that manually. What you really want to do it use a library such as the adLDAP library, and use that to do all sorts of fancy things.

adLDAP

Here’s the feature list:

  • User authentication
  • Group management
  • User management
  • Contact management
  • Exchange mailbox creation

It’s really worth checking out. They even provide info on how to achieve a seamless signon for within your domain. Here’s the IIS/PHP instructions:

Format the machine and install Linux (recommended), or remove anonymous access from the directory with the IIS management console, the username is available with $_SERVER[“LOGON_USER”].

Seamless authentication with Apache on Windows can be achieved with mod-auth-sspi

[ From: Seamless Authentication - adLDAP Wiki ]

So, there you have it. Active Directory authentication with PHP.