Difference between #7 and #5 of How to use ldap in UserIdentity for authentication

unchanged
Title
How to use ldap in UserIdentity for authentication
unchanged
Category
Tutorials
changed
Tags
AuthenticationAuthentication, LDAP
changed
Content
It took me a whileYii does not have an LDAP class itself, but
its very easy to get ldap auth working with yii, so I write it down
here, maybe it can be of some use.implement LDAP in the stock
UserIdentity class.

Yii does not have a ldap class by itself, but you can extend it for example
with Zend classes. To authenticate users at you page via ldap,
changeTo do so, open your
protected/components/UserIdentity.php and remove or comment out the
code in the following way:

On top of the file add:authenticate() method, before replacing it
with this:
~~~
[php]
    Yii::import('application.vendors.*');
    require_once('Zend/Ldap.php');$options =
Yii::app()->params['ldap'];
$dc_string = "dc=" . implode(",dc=",$options['dc']);
 
$connection = ldap_connect($options['host']);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
 
if($connection)
{
    $bind = ldap_bind($connection,
"uid={$this->username},ou={$options['ou']},{$dc_string}",
$this->password);
 
    if(!$bind) $this->errorCode = self::ERROR_PASSWORD_INVALID;
    else $this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
~~~

Delete or comment out everything in the authenticate() function.
ThenOnce you have done this, open up your configs/main.php file,
and add the following to the 'params' array at the bottom of the
file:
~~~
[php]
    $options ='ldap' => array(
            'host'              => 'your.ldap.host.com',
            'username'          => 'your_admin_users_username',
            'password'          => 'your_admin_users_password',
            'baseDn'            => 'your_base_dn',
            'useStartTls'        => true, # if you need startTls
    );
    $ldap = new Zend_Ldap($options);
    try{
           
$ldap->bind("cn=".$this->username.",your_base_dn",
$this->password);
            $auth=true;
    }
    catch (Exception $e){
            $auth=false;
    }
    if($auth===true)
    {
            $this->errorCode=self::ERROR_NONE;
    }
    return !$this->errorCode;
    'host' => 'hostname',
    'ou' => 'organisational-unit', // such as "people" or
"users"
    'dc' => array('example','com'),
),
~~~

For this to work you need Exception.php, Ldap.php
andReplace the Ldap folder fromhost with
the library folderhostname of the LDAP server, ou
with the organisational unit you want to authenticate against (most LDAP servers
use a Zend installation inbroad terminology, such as
"people"), and dc with the folder protected/vendors/Zend


base DN.  (For example array("ucla","edu") //
ucla.edu)