I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 (adLDAP does it on Apache). Anyone had done anything similar, with success?
LDAP extracts information from AD with a simple, string-based query. LDAP can also share the extracted information (such as usernames and passwords) with connected devices or applications. Using LDAP eliminates the need for users to manually enter a string of LDAP queries to retrieve information from AD.
LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.
LDAP v3 supports three types of authentication: anonymous, simple and SASL authentication.
Importing a whole library seems inefficient when all you need is essentially two lines of code...
$ldap = ldap_connect("ldap.example.com"); if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) { // log them in! } else { // error message }
You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:
use LdapTools\Configuration; use LdapTools\DomainConfiguration; use LdapTools\LdapManager; $domain = (new DomainConfiguration('example.com')) ->setUsername('username') # A separate AD service account used by your app ->setPassword('password') ->setServers(['dc1', 'dc2', 'dc3']) ->setUseTls(true); $config = new Configuration($domain); $ldap = new LdapManager($config); if (!$ldap->authenticate($username, $password, $message)) { echo "Error: $message"; } else { // Do something... }
The authenticate call above will:
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With