PHP code example of mindcontact-dev / yii2-ldap-auth

1. Go to this page and download the library: Download mindcontact-dev/yii2-ldap-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mindcontact-dev / yii2-ldap-auth example snippets


'components' => [
    ...
    'ldapAuth' => [
        'class' => '\MindContact\Yii2LdapAuth\LdapAuth',
        'host' => 'ldap-server',
        'baseDn' => 'dc=shihadeh,dc=intern',
        'searchUserName' => 'cn=admin,dc=shihadeh,dc=intern',
        'searchUserPassword' => 'test1234',

        // optional parameters and their default values
        'ldapVersion' => 3,             // LDAP version
        'protocol' => 'ldap://',       // Protocol to use           
        'followReferrals' => false,     // If connector should follow referrals
        'port' => 389,                  // Port to connect to
        'loginAttribute' => 'cn',      // Identifying user attribute to look up for
        'ldapObjectClass' => 'inetOrgPerson',  // Class of user objects to look up for
        'timeout' => 10,                // Operation timeout, seconds
        'connectTimeout' => 5,          // Connect timeout, seconds
        'roleMappings' => [
            'cn=Admins,ou=Groups,dc=shihadeh,dc=intern' => 'admin',
            'cn=Maintaners,ou=Groups,dc=shihadeh,dc=intern' => 'operator',
        ],
        'isEnabled' => false,
        'demoUser' => [
            'Id' => 'demo.user',
            'Username' => 'Demo User',
            'Email' => '[email protected]',
            'Dn' => 'cn=demo_user,dc=shihadeh,dc=intern',
            'Roles' => ['admin']
        ]
    ],
    ...
    
    'user' => [
        'identityClass' => '\MindContact\Yii2LdapAuth\Model\LdapUser',
        'enableSession' => true,
        'enableAutoLogin' => true,
    ],
    ...
]

use MindContact\Yii2LdapAuth\Model\LdapUser;

...

public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = LdapUser::findIdentity($this->username);

        if (!$user || !Yii::$app->ldapAuth->authenticate($user->getDn(), $this->password) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

...

public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login(
            LdapUser::findIdentity($this->username),
            $this->rememberMe
                ? 3600*24*30 : 0
        );
    }
    return false;
}

Yii::$app->ldapAuth->authenticate($user->getDn(), $this->password, 'cn=auth-user-group')