Ldap Authentication using Laravel 7 — Phpflow.com

Parvez Alam
2 min readMar 8, 2021

This tutorial help to ldap authentication using laravel 7.I am creating some apis that ll use by react application to do some operations. So I need to authenticate user to restrict some rest endpoints. The adldap2 package is used to management and authentication to LDAP servers.

Use case of LDAP with laravel 7

I need to validate laravel api using basic auth with no database. We do not have requirement to store user info the table so I ll use noDatabaseService provider. We ll authenticate POST/PUT and DELETE http apis against the user credentials. We ll pass basic authentication using http client.

The requirement is to use username instead of email for authentication. For username authentication I need to connect to the company’s active directory.

The Pre-Requisite are:

  • PHP 7
  • The Laravel 7 application
  • ldap_connect package enabled into php.ini
  • The adldap package for LDAP authentication

Integrate Adldap2 with Laravel 7

Let’s integrate LDAP server with laravel application.We ll use adldap2 third party package to integrate Ldap with Laravel 7.

we will install adldap2 into our existing laravel application. Made entry "adldap2/adldap2-laravel": "^6.1" into the composers.json file and run below command to install.

Let’s publish the auth.php and ldap_auth.php :

We do not change ldap.php file.We ll made some changes into ldap_auth.php file -

Modify ldap_auth.php file

Setting your LDAP configurations

We ll made following ldap configuration information into .env file.

Above configuration variables also found into the config/ldap.php, You can add there or use .env file to manage them.

Laravel 7 appliaction Intag

First, create a middleware for basic authentication and write logic to authorize user.

This command will place a new Adldap class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied credentials input matches a specified value. Otherwise, we will redirect the users back to the home URI:

We have used authLdapUser() and to check user is authorize or not.

We have used getLdapUser() and method to get user information from LDAP server, I have created this method into Helper.php file.

Added middleware kernel.php file :

Made routes entry into api.php file:

Created method into the homeController.php controller file:

Laravel Run and Test API

Let’s run the website and try to log in.

php artisan serve

Visit http://localhost:8000/api/v1/test_ldap in your favorite browser.

Originally published at https://www.phpflow.com on March 8, 2021.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/