Skip to content

Instantly share code, notes, and snippets.

@michaelachrisco
Last active November 4, 2015 20:51
Show Gist options
  • Save michaelachrisco/c4718f5ff429c9063c98 to your computer and use it in GitHub Desktop.
Save michaelachrisco/c4718f5ff429c9063c98 to your computer and use it in GitHub Desktop.
Custom sample Microsoft LDAP (AD) Controller for authentication for Laravel 5.1 (handshake version)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
/// Microsoft LDAP Controller for authentication
class LDAPAuthController {
public function handshake($username, $password, $authEmail)
{
if(empty($username) or empty($password)){
Log::error('Error binding to LDAP: username or password empty');
// return false;
}
// if user used .domain.local, replace it with email
// TODO: Use server vars from apache instead (later on)
$transformedAuthEmail = str_replace("domain.local", "domain.org", $authEmail);
$ldapconn=ldap_connect("999.99.9.999") or die("Could not connect to LDAP server.");
$result = false;
if ($ldapconn)
{
try{
// bind the connection
$bind = @ldap_bind($ldapconn, $username, $password);
if($bind){
$result = ldap_search($ldapconn,"OU=FOO,DC=foo,DC=local", "mail={$transformedAuthEmail}", array('distinguishedname', 'memberof'));
$entries = ldap_get_entries($ldapconn, $result);
if (empty($entries) || $entries['count']==0){
ldap_unbind($ldapconn);
//Incorrect email address
return false;
} else{
$LDAPUserName = $entries[0]['distinguishedname'][0];
//$LDAPUserGroup = $entries[0]['memberof'];optional user membership
// valid credentials
ldap_unbind($ldapconn);
return $LDAPUserName;
}
}
else{
// invalid credentials
ldap_unbind($ldapconn);
return false;
}
}
//Blow up and Log
catch(Exception $e){
Log::error($e);
return false;
}
// ldap_unbind($ldapconn);
}
else {
Log::error('Error connecting to LDAP.');
return false;
}
ldap_unbind($ldapconn);
}
public function authenticate($username, $password)
{
if(empty($username) or empty($password)){
// Log::error('Error binding to LDAP: username or password empty');
return false;
}
$ldapconn=ldap_connect("999.9.99.999") or die("Could not connect to LDAP server.");
// ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); //Option for OpenLDAP (testing purposes)
$result = false;
if ($ldapconn)
{
$user_path=$this->handshake('admon_username','admin_pass', $username);
if ($user_path==false){
return false;
}
try{
// bind the connection
$bind = @ldap_bind($ldapconn, $user_path, $password);
if($bind){
// valid credentials
ldap_unbind($ldapconn);
return true;
}
else{
// invalid credentials
ldap_unbind($ldapconn);
return false;
}
}
//If username/password are not correct, dont login
catch(Exception $e){
return false;
}
// ldap_unbind($ldapconn);
}
else {
Log::error('Error connecting to LDAP.');
}
ldap_unbind($ldapconn);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment