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.

$composer update

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

php artisan vendor:publish --provider="Adldap\Laravel\AdldapServiceProvider"
php artisan vendor:publish --provider="Adldap\Laravel\AdldapAuthServiceProvider"

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

<?php

return [

    'connection' => env('LDAP_CONNECTION', 'default'),

    'provider' => Adldap\Laravel\Auth\NoDatabaseUserProvider::class,

    'model' => Adldap\Models\User::class,


    'rules' => [

        // Denys deleted users from authenticating.

        Adldap\Laravel\Validation\Rules\DenyTrashed::class,

        // Allows only manually imported users to authenticate.

        // Adldap\Laravel\Validation\Rules\OnlyImported::class,

    ],

    'scopes' => [

        // Only allows users with a user principal name to authenticate.
        // Suitable when using ActiveDirectory.
        // Adldap\Laravel\Scopes\UpnScope::class,

        // Only allows users with a uid to authenticate.
        // Suitable when using OpenLDAP.
        // Adldap\Laravel\Scopes\UidScope::class,

    ],

    'identifiers' => [

        'ldap' => [

            'locate_users_by' => 'samaccountname',

            'bind_users_by' => 'distinguishedname',

        ],

        'database' => [

            'guid_column' => 'objectguid',

            'username_column' => 'username',

        ],


        'windows' => [

            'locate_users_by' => 'samaccountname',

            'server_key' => 'AUTH_USER',

        ],

    ],

    'passwords' => [
        'sync' => env('LDAP_PASSWORD_SYNC', false),

        'column' => '',

    ],

    'login_fallback' => env('LDAP_LOGIN_FALLBACK', false),

    'sync_attributes' => [

        'email' => 'userprincipalname',

        'name' => 'cn',

    ],

    'logging' => [

        'enabled' => env('LDAP_LOGGING', true),

        'events' => [

            \Adldap\Laravel\Events\Importing::class                 => \Adldap\Laravel\Listeners\LogImport::class,
            \Adldap\Laravel\Events\Synchronized::class              => \Adldap\Laravel\Listeners\LogSynchronized::class,
            \Adldap\Laravel\Events\Synchronizing::class             => \Adldap\Laravel\Listeners\LogSynchronizing::class,
            \Adldap\Laravel\Events\Authenticated::class             => \Adldap\Laravel\Listeners\LogAuthenticated::class,
            \Adldap\Laravel\Events\Authenticating::class            => \Adldap\Laravel\Listeners\LogAuthentication::class,
            \Adldap\Laravel\Events\AuthenticationFailed::class      => \Adldap\Laravel\Listeners\LogAuthenticationFailure::class,
            \Adldap\Laravel\Events\AuthenticationRejected::class    => \Adldap\Laravel\Listeners\LogAuthenticationRejection::class,
            \Adldap\Laravel\Events\AuthenticationSuccessful::class  => \Adldap\Laravel\Listeners\LogAuthenticationSuccess::class,
            \Adldap\Laravel\Events\DiscoveredWithCredentials::class => \Adldap\Laravel\Listeners\LogDiscovery::class,
            \Adldap\Laravel\Events\AuthenticatedWithWindows::class  => \Adldap\Laravel\Listeners\LogWindowsAuth::class,
            \Adldap\Laravel\Events\AuthenticatedModelTrashed::class => \Adldap\Laravel\Listeners\LogTrashedModel::class,

        ],
    ],

];

Setting your LDAP configurations

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

ADLDAP_CONNECTION=default
ADLDAP_CONTROLLERS=ldap.domain.com
ADLDAP_BASEDN=dc=example,dc=com
ADLDAP_USER_ATTRIBUTE=uid
ADLDAP_USER_FORMAT=uid=%s,dc=example,dc=com

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.

php artisan make:middleware Adldap

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:

<?php

namespace App\Http\Middleware;
use App\Helper\Helper;
use Closure;
use Log;

class Adldap
{
    
    use Helper;
    public $attributes;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        $authenticated = false;
       
         if ($email = $request->getUser() && $password = $request->getPassword()) {
            Log::info("Authenticate user using basic auth");
            $credentials = array(
                'samaccountname' => $request->getUser(),
                'password' => $request->getPassword()
            );
            //
            $authenticated = $this->authLdapUser($credentials);
            
            if($authenticated) {
                $user = $this->getLdapUser($request->getUser());
            }
         }
        if (!empty($user)) {
            $authenticated = true;
            if(!$this->checkRoles($user['groups'], $role)) {
                return response("User is not authorize for this request.", 401);
            }
            $request->attributes->add(['user_groups' => $user['groups']]);
            return $next($request);
        }

        if (!$authenticated) {
            return response("Unauthorized: Access is denied due to invalid credentials.", 401);
        }
    }
}

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

private function authLdapUser($credentials) {
        try {
            if(Auth::attempt($credentials)) {
                return true;
            }
        } catch (\Exception $e) {
            Log::critical($e);
            return false;
        }
   }

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

private function getLdapUser($user_name) {
        $user = array();
        try {
            $resp = $this->ldap->search()->users()->find($user_name);
            if (!empty($resp)) {
                $user['name'] = $resp->getName();
                $user['uid'] =  $resp->getDistinguishedname();
                $user['email'] = $resp->getUserprincipalname();
                $user['groups'] = $resp->getMemberof();
            }
            return $user;
        }  catch (\Exception $e) {
            Log::critical($e);
            return $user;
        }

    }

Added middleware kernel.php file :

protected $routeMiddleware = [
        'BasicAuth' => \App\Http\Middleware\BasicAuth::class,
    ];

Made routes entry into api.php file:

Route::middleware(["BasicAuth:admin"])->group(function () {
    Route::get('test_ldap', 'HomeController@helloAdmin');
});

Created method into the homeController.php controller file:

public function helloAdmin() {
     
    return $this->jsonpSuccess('Hello admin');
    
}

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 *