Goal: Use LDAP and PHP to authenticate with Active Directory

Difficulty: Moderate

Prerequisites: FastCGI and IIS Web Server, PHP LDAP module, Working knowledge of PHP

Many times in enterprise environments you already have an active directory server and all the users you would ever want to access something have an account there. So why go through the trouble of creating yet another authentication system? Why not just leverage those accounts, that way you eliminate another system to remember your password for, use your active directory system to enforce password strength, account lockouts, and all those other built in features that come with active directory.

Some notes about the implementation below: I implemented this on a windows 2012 server with IIS and PHP over FastCGI. Make sure that you have enabled / compiled the LDAP module in php. Where i defined the $adServer variable you can specify either the host name of the domain controller or the ip address. I also included a simple echo in the example to show you how to access objects of the active directory account logging in as well as a var dump so that you can see what the object contains. Please remove these once you know the information you are after.

<?php
/**
 * Created by Joe of ExchangeCore.com
 */
if(isset($_POST['username']) && isset($_POST['password'])){

    $adServer = "ldap://domaincontroller.mydomain.com";
	
    $ldap = ldap_connect($adServer);
    $username = $_POST['username'];
    $password = $_POST['password'];

    $ldaprdn = 'mydomain' . "\\" . $username;

    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

    $bind = @ldap_bind($ldap, $ldaprdn, $password);


    if ($bind) {
        $filter="(sAMAccountName=$username)";
        $result = ldap_search($ldap,"dc=MYDOMAIN,dc=COM",$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 = "Invalid email address / password";
        echo $msg;
    }

}else{
?>
    <form action="#" method="POST">
        <label for="username">Username: </label><input id="username" type="text" name="username" /> 
        <label for="password">Password: </label><input id="password" type="password" name="password" />        <input type="submit" name="submit" value="Submit" />
    </form>
<?php } ?> 

Comments

Leave a Reply



(Your email will not be publicly displayed.)



Search