Laravel 4 doesn't have LDAP authentication in built in its core. So this is a quick and dirty way to add it to your app. It is using internal LDAP PHP functions, so you'll need to install the php5-ldap
package:
Configuration for your app/conf/auth.php:
'ldap_tree' => 'OU=anything,DC=domain,DC=com',
'ldap_server' => 'your.ldap.server.com',
This is a LDAP class to be used by your controllers:
class LDAP {
public static function authenticate($username, $password)
{
if(empty($username) or empty($password))
{
Log::error('Error binding to LDAP: username or password empty');
return false;
}
$ldapRdn = static::getLdapRdn($username);
$ldapconn = ldap_connect( Config::get('auth.ldap_server') ) or die("Could not connect to LDAP server.");
$result = false;
if ($ldapconn)
{
$ldapbind = @ldap_bind($ldapconn, $ldapRdn, $password);
if ($ldapbind)
{
$result = true;
} else {
Log::error('Error binding to LDAP server.');
}
ldap_unbind($ldapconn);
} else {
Log::error('Error connecting to LDAP.');
}
return $result;
}
public static function getLdapRdn($username)
{
return str_replace('[username]', $username, 'CN=[username],' . Config::get('auth.ldap_tree'));
}
}
And an AuthController to process the login on your app:
class AuthController extends Controller {
public function __construct(LDAP $ldap)
{
$this->ldap = $ldap;
}
public function login()
{
if ( $this->ldap->authenticate( Input::get('email'), Input::get('password') ) )
{
$user = User::where('email', Input::get('email'))->first();
Auth::login( $user );
return Redirect::to('home');
}
return Redirect::refresh()->with('error', 'User and/or password are incorrect.');
}
public function logout()
{
if ( ! Auth::guest())
{
Auth::logout();
return Redirect::to('message')
->with('message', 'You just logged out.');
}
return Redirect::to('login');
}
}
Note that this controller is using Dependency Injection for the LDAP class, it will be injected automatically by Laravel.