Ldap Authentication using Laravel 7

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 information into the table, So I will use noDatabaseService provider. We will authenticate POST/PUT and DELETE http apis against the user credentials. We will 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 file.
  • The adldap package for LDAP authentication.

Integrate Adldap2 with Laravel 7

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

First, 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 :

Above command will create both configurations file into the config file. We do not change ldap.php file. We will made some changes into ldap_auth.php file –

Modify ldap_auth.php file

Setting your LDAP configurations

We will 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 application with Adldap

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.