Thursday, 13 September 2018

Authenticate user through LDAP, Active Directory

Please go through the code below - Codeigniter
--------------------------------------------------------------------------------------

Config - define
---------------------------------------------------
define('ldap_serverhost', '192.168.24.31');
define('ldap_basedn', 'domainname');


Controller code - Login
----------------------------------------------------
$username = $this->input->post('userid', TRUE);
$password = $this->input->post('password', TRUE);
$entries = ldap_connention($username, $password);


Helper code - custom_helper
----------------------------------------------------

if (!function_exists('ldap_connention')) {
    /**
     * Create LDAP CONNECTION
     *
     */
    function ldap_connention($handle, $password)
    {

        $server = ldap_serverhost;
        $basedn = ldap_basedn;
        $dn = ldap_basedn . "\\" . $handle;

        $connect = ldap_connect($server);
        ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);

//var_dump(ldap_bind($connect, $dn, $password));
        if ($ds = @ldap_bind($connect, $dn, $password)) {
            $filters = "(samaccountname=$handle)";
            //    $filters = "(cn=*)"; // get all results
            $results = ldap_search($connect, "dc=" . ldap_basedn . ",dc=COM", $filters) or exit("unable tosearch");
            $entries = ldap_get_entries($connect, $results);
            if (count($entries) > 0) {
                return $entries;
            } else {
                return 0;
            }

        } else {
            return 0;
        }


    }

No comments:

Post a Comment