If you are working in an organisation, you will be aware about Active Directory that provides all sorts of functionality like folder access, authentication, group and user management.

Recently, I was developing this web app at work and wanted to integrate LDAP login rather than managing a separate login for users. I did some research and found out that it is pretty easy. There are plugins like https://github.com/DirectoryTree/LdapRecord-Laravel which provides seamless integration. However, I was just looking for something like, to verify that the email and password provided by the user matches with the Active Directory credentials.

So, I tried the native php implementation and it worked pretty well. Below is my code

public function authenticate()
{
    $credentials = $this->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    $adServer = "ldap://192.168.1.1"; //ldap server ip address

    $ldap = ldap_connect($adServer);

    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

    try 
    {
        $bind = @ldap_bind($ldap, $this->email, $this->password);
        if ($bind) {
            $user = User::whereEmail($this->email)->first();
            if ($user)
            {
                Auth::login($user);
                redirect()->intended(route('home'));
            }
            else
            {
                $this->addError('email', 'Access denied');
            }
        } else {
            $this->addError('email', 'Invalid credentials');
        }
    }
    catch (Exception $e)
    {
        // handle exception here
    }
}

When the user fills and submit the login form, I call the authenticate function to verify the credentials. I also have a separate users table to limit access to certain users. After successful AD login, the email is checked with the users table and if the email exists, the user is granted access to application.