PHP on Linux authenticate users with a Windows Server Active Directory

8 Aug 2018 | PHP on Linux authenticate users with a Windows Server Active Directory |

A common request when building INTRANET web applications is to have users use only one  common shared set of  login credentials. Typically in most small and medium businesses this means that logging into a Windows Server of some kind to access the network.  Windows Servers use Active Directory (AD) ,which is  basically Microsoft’s glorified LDAP server with a slew of additional features needed for  coroporate and enterprise users.  We can leverage this by using PHP’s LDAP module to perform the login check for us..

Git Hub Code: https://github.com/acbrandao/PHP/tree/master/phpLDAPWindows

IF you’re building your application in PHP a very easy way to do this is simply to use PHPs LDAP library and then simply call with the proper functions.  Let’s detail the steps below. I’ll be doing this from a PHP 5 , Debian installation.

LDAP tends to be tied into the Windows AD Domain Name System to allow integrated quick lookups and fast resolution of queries. LDAP generally runs on port 389 and like other protocols tends to usually conform to a distinct set of rules (RFC’s).

Step 1. Get the LDAP information (LDAP Connection URL)  from your Windows Active Directory.

First we need to verify which Windows Active directory we will be authenticating against. If your in a very large corporate environment, you may need the help of an SA (System administrator) to help guide you. Basically, the first thing you need is to know is the Domain which this users is associated with.

Essetially you need to figure out with the LDAP Connection URL is , and this requires a bit more information about how the Windows Network is configured, Typically its something like ,

CN=Users,DC=corp,DC=domain,DC=local

then you wold combine this with the URL of the Windows AD server

 LDAP://dc1.corp.domain.com/  
or 
 LDAP://10.0.1.3/

To query for a particular user.  If you have accesss to the Windows Server form the command line run.

C:\Users\Administrator> dsquery user -name To*
"CN=Tony Jones,CN=Users,DC=Domain,DC=local"
"CN=Tony Smith,CN=Users,DC=Domain,DC=local"

Alternatively from the  Windows server desktop try

Active directory server -> Choose the Organization Unit OU -> Right Click -> Properties -> AttributeEditor -> DistinguishedName

The above information is necessary so you can fill in the details of the PHP script below.

Step 2. Verify PHP LDAP Library installed and enabled.

You can do this by running a simple viewing the PHP info to see which  loaded modules are currently available on your server.

Create a simple PHP file on your web server , call it test.php or something like that. When you run it it will display all the information that  PHP /Apache has configured.

<?php
phpinfo();
?>

Run that file from your browser http://localhost/test.php  and search for an entry like LDAP (Typically midway down the page  between JSON and LIBXML ), if you see something like the screen below.

PHP info showing LDAP module is enabled.

If you do not see this enabled, then you may want to have it added to your PHP/Apache server . The simplest way if you have a typical Debian Linux access to your server’s shell is to run the command.  For other flavors of Linux  like Redhat/Centos a similar yum command should be available.

sudo apt-get install php5-ldap

or for PHP 7

sudo apt-get install php-ldap

The command should install the necessary library and restart the server, once again re-test that it’s enabled by running the above test.php and confirming the LDAP module is correctly loaded.

Step 3. Test PHP Login against Windows AD

Finally Upload this test LDAP script to your server and save it as ldap.php (or similar name) which does the follow…

  • Usig the supplied LDAP information , don’t forget to REPLACE the DOMAIN_FQDN and LDAP_SERVER define with your actual credentials
  • Takes the user supplied username and password and
  • Issues an LDAP bind  to see if that’s a valid user
  • You get back either a True or False from the AD and you can proceed from there.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
define('DOMAIN_FQDN', 'YOUR_DOMAIN.local'); //Replace with REAL DOMAIN FQDN
define('LDAP_SERVER', '10.0.1.3');  //Replace with REAL LDAP SERVER Address

//Basic Login verification
if (isset($_POST['submit']))
{
    $user = strip_tags($_POST['username']) .'@'. DOMAIN_FQDN;
    $pass = stripslashes($_POST['password']);

    $conn = ldap_connect("ldap://". LDAP_SERVER ."/");

    if (!$conn)
        $err = 'Could not connect to LDAP server';

    else
    {
//        define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);  //Already defined in PHP 5.x  versions
        ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);

        $bind = @ldap_bind($conn, $user, $pass);

        ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error);

        if (!empty($extended_error))
        {
            $errno = explode(',', $extended_error);
            $errno = $errno[2];
            $errno = explode(' ', $errno);
            $errno = $errno[2];
            $errno = intval($errno);

            if ($errno == 532)
                $err = 'Unable to login: Password expired';
        }

        elseif ($bind)
        {
      //determine the LDAP Path from Active Directory details
            $base_dn = array("CN=Users,DC=". join(',DC=', explode('.', DOMAIN_FQDN)), 
                "OU=Users,OU=People,DC=". join(',DC=', explode('.', DOMAIN_FQDN)));

            $result = ldap_search(array($conn,$conn), $base_dn, "(cn=*)");

            if (!count($result))
                $err = 'Result: '. ldap_error($conn);

            else
            {
                echo "Success";
        /* Do your post login code here */
            }
        }
    }

    // session OK, redirect to home page
    if (isset($_SESSION['redir']))
    {
        header('Location: /');
        exit();
    }

    elseif (!isset($err)) $err = 'Result: '. ldap_error($conn);

    ldap_close($conn);
}
?>
<!DOCTYPE html>
<head>
<title>PHP LDAP LOGIN</title>
</head>
<body>
<div align="center">
<h3>Login</h3>

<div style="margin:10px 0;"></div>
<div title="Login"  id="loginbox">
    <div style="padding:10px 0 10px 60px">
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" id="login" method="post">
        <table><?php if (isset($err)) echo '<tr><td colspan="2" class="errmsg">'. $err .'</td></tr>'; ?>
            <tr>
                <td>Login:</td>
                <td><input type="text" name="username" autocomplete="off"/></td>
            </tr>
            <tr
                <td>Password:</td>
                <td><input type="password" name="password"  autocomplete="off"/></td>
            </tr>
        </table>
        <input class="button" type="submit" name="submit" value="Login" />
    </form>
    </div>
</div>
</div>
</body>
</html>

Security Considerations:

By default, LDAP traffic is transmitted unsecured; this may or may not be a concern in an Intranet setting, for maximum safety use SSL technology to encrypt the traffic. Also most Windows Server AD will LOCK the account after n unsuccessful re-tries so be aware of this when testing your PHP login script.

Hopefully this will provide an easy way to integrate your PHP scripts with your INTRANET servers, making it easier to keep manage user accounts and access from one spot.

11 thoughts on “PHP on Linux authenticate users with a Windows Server Active Directory

  1. Reply Sam Luii Aug 8,2018 2:07 pm

    How can you map this to a MySQL server? that is how can authentication be used with a mySQL table

  2. Reply Ramesh Sanjiv Aug 14,2018 2:26 pm

    How do you setup an SSL connection to make sure that the credentials are secured

  3. Reply Bryan Feb 27,2019 9:59 am

    Thanks, this works far better than any other process I’ve seen and takes far less configuration. Obviously we need to set up sessions with this but this is a great starting point.

    I should note on line 80 you are missing a closing bracket.

  4. Reply Mike Apr 2,2019 4:28 am

    Is any option to check if user can login or what kind of user we have – without getting username and password? By using some “server variable”, “server user id”, “server user login”, “server user fingerprint”? Our goal is that when user is opening website on localhost we know that this in “Mark Twain” ex. and we have nice screen for him – without username and password.

    • Reply Tony B. Apr 4,2019 11:25 am

      I think you should be able to query the ACTIVE Directory server as to USER ATTRIBUTES, this does require that the folks that created the account properly assigned those attributes. Take a look here at some attributes available on active driectory http://www.kouti.com/tables/userattributes.htm . Once you have gotten the attribute for a user then you can decide what to show.

      I know most companies don’t add any extra attributes, besides maybe the department or description , maybe you can key off those two.?

  5. Reply Frank Jul 29,2020 8:27 am

    Similar to the commend about a missing bracket on line 80…The code is missing a closing angle bracket for the tr tag (>) on line 85. Maybe it was originally line 80 and is now line 85.

  6. Pingback: php ldap login - Credit One

  7. Pingback: Active Directory Php Logga In – Sweden Logga In

  8. Pingback: Php Authenticate With Active Directory? All Answers - Barkmanoil.com

  9. Pingback: Active Directory Php Logga In - SwVast

Leave a Reply to Bryan Cancel Reply