Wednesday, September 23, 2015

Active Directory authentication with PHP

I'm running an intra site with contents that require users to log in. Many tutorials and code snippets I've found online work only if you have set your LDAP server signing requirements group policy to None. Mine is set to Require signing as by default in Server 2008 R2. It took me surprisingly long to get this rather short and simple piece of code to work, so I thought to share it with you. This function returns true if username and password are correct (for any AD user), else false. Tested on IIS 7.5.

function login_ldap($username, $password) {
    $ldap = ldap_connect("ldap://example.local");
    if ($ldap === false) return false;
    // set the LDAP protocol
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    putenv('LDAPTLS_REQCERT=never');
    // start SSL
    ldap_start_tls($ldap);
    // ldap_bind will return true if user authenticated, else false
    $bind = @ldap_bind($ldap, "EXAMPLE\\" . $username, $password);
    ldap_close($ldap);
    return $bind;
}

No comments:

Post a Comment