Easy 8 Steps to Setup LDAP in Laravel Application

  • By Aelum Consulting
  • May 5, 2021
  • 5427 Views

Understanding LDAP in Laravel Application

LDAP (Lightweight Directory Access Protocol) is a directory services protocol that is used for interacting with directory services.

One of the examples of directory services is Active Directory (AD) which is Microsoft’s proprietary directory service used to manage and store information about the devices, users, objects within an organization’s network.

So, here we will understand how to do LDAP connectivity in laravel to authenticate users in the active directory.

Easy steps to setup LDAP in Laravel Application

LDAP server with Laravel - Stack Overflow

Step 01: Install the third-party LDAP package adldap2 in your laravel application using the below command.

composer require adldap2/adldap2-laravel

Step 02: Publish the installed package using the below command.

PHP artisan vendor:publish –provider=”Adldap\Laravel\AdldapServiceProvider”

Step 03: Most importantly, uncomment the dll for LDAP from the php.ini file first otherwise it will throw an error.

Step 04: Configure the following settings in ldap.php inside your config folder.

Inside Settings:
‘hosts’ => explode(‘ ‘, env(‘LDAP_HOSTS’, ‘ldap.forumsys.com’)),
‘base_dn’ => env(‘LDAP_BASE_DN’, ‘dc=example,dc=com’),
‘username’ => env(‘LDAP_USERNAME’),
‘password’ => env(‘LDAP_PASSWORD’)

For an anonymous user, leave username and password it as it otherwise mentions the username and password.

Step 05: At step 4 the configuration has been done, now check the connection by running a query in the login controller to fetch user records from the active directory. curie is a test user for ‘ldap.forumsys.com’ directory.

$search = Adldap::search()->where(‘uid’, ‘=’, ‘curie’)->get(); //Here uid is DN

Step 06: For authentication use the below sample code inside login controller.

$username= $request->input(‘name’);
$password= $request->input(‘name’);
$user_format = env(‘ADLDAP_USER_FORMAT’, ‘uid=%s,’.’dc=example,dc=com’);
//change DN and base dn as per the requirement
$userdn = sprintf($user_format, $username);
Adldap::auth()->bind($userdn, $password);
if(Adldap::auth()->attempt($userdn, $password, $bindAsUser = true))
{
echo ‘Login successful’;
}
else
{
echo “Username or password invalid”;
}

Step 07: After having a successful test connection don’t forget to replace ‘ldap.forumsys.com’ with your actual directory address.

Step 08: Let’s run the application and try to log in.

Thanks For Reading.

Blog Written By: Aayushi Agrawal | Senior Php Developer