Authenticating users against Active Directory with PHP

A co-worker of mine asked how this can be done, since I’ve already had some experience querying AD with Java and PHP. It’s been some time ago so I had to think about a little but then I realized it’s easy. Just use LDAP bind!

Consider the following PHP code snippet:

$ldaphost = ‘ldap://dc.mycompany.local’;
$ldapport = 389;

$user = ‘DOMAIN\user’;
$password = ‘password’;

$ldapconn = @ldap_connect( $ldaphost, $ldapport );
if( $ldapconn )
{

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

$ok = @ldap_bind( $ldapconn, $user, $password );
if( $ok )
{
ldap_unbind( $ldapconn );
}
else
{
echo ‘Failed to bind to LDAP server:’ . “\n”;
echo ldap_error( $ldapconn ) . “\n”;
}
}
else
{
echo ‘Failed to connect to LDAP server’ . “\n”;
}

It is important to prefix the user’s name with the domain otherwise it won’t accept it and obviously in real life you’d want to use LDAPS and not send the password over the wire in clear text, but the basic idea is the same.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: