Adldap2 / Adldap2-Laravel

LDAP Authentication & Management for Laravel
MIT License
910 stars 184 forks source link

Can't login with auth driver #248

Closed handrej closed 7 years ago

handrej commented 7 years ago

Hi Steve, I appreciate the effort you and your team put into creating Adldap2 but I always run into the same issue after days of trial and error. I've tried getting it to work in my own project as well as an example project but every time I get the same result.

My configuration for the test project looks like this:

adldap.php

return [

    'connections' => [
        'default' => [

            'auto_connect' => true,

            'connection' => Adldap\Connections\Ldap::class,

            'schema' => Adldap\Schemas\ActiveDirectory::class,

            'connection_settings' => [

                'domain_controllers'    => ['xxxx.xxxx.xxxx.xx'],
                'base_dn'               => 'ou=xx,ou=xx,ou=xxxx,o=xxxx',
                'admin_username'        => '',
                'admin_password'        => '',
                'account_prefix'        => 'cn=',
                'account_suffix'        => ',ou=xx,ou=xx,ou=xxxx,o=xxxx',
                'port'                  => 389,
                'follow_referrals'      => false,
                'use_ssl'               => false,
                'use_tls'               => false,
                'timeout'               => 5,

            ],
        ],
    ],
];

adldap_auth.php

return [

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

    'username_attribute' => ['username' => 'samaccountname'],

    'limitation_filter' => env('ADLDAP_LIMITATION_FILTER', ''),

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

    'password_key' => env('ADLDAP_PASSWORD_KEY', 'password'),

    'password_sync' => env('ADLDAP_PASSWORD_SYNC', true),

    'login_attribute' => env('ADLDAP_LOGIN_ATTRIBUTE', 'samaccountname'),

    'windows_auth_attribute' => ['samaccountname' => 'AUTH_USER'],

    'bind_user_to_model' => env('ADLDAP_BIND_USER_TO_MODEL', true),

    'sync_attributes' => [

        'name' => 'cn',

    ],

    'select_attributes' => [

        //

    ],

];

auth.php

return [

    'driver' => 'adldap',

    'model' => App\User::class,

    'table' => 'users',

    'password' => [
        'email'  => 'emails.password',
        'table'  => 'password_resets',
        'expire' => 60,
    ],

];

User.php

namespace App;

use Adldap\Laravel\Traits\AdldapUserModelTrait;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, AdldapUserModelTrait; // Insert trait here

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'username', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

create_users_table.php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('username')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

AuthController.php


namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Adldap;
use Auth;

class AuthController extends Controller
{

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    protected $username = 'username';

    public function postLogin(Request $request)
    {

        $username = $request['username'];
        $password = $request['password'];

/*
 User::create([
                    'name' => $username,
                    'username' => $username,
                    'password' => $password,
                ]);
*/

        if (Adldap::auth()->attempt( $username, $password) )  {

            return redirect()->intended('/');
        }

        return redirect()->back()->withErrors(
            'Username and/or Password are not matching!'
        );
    }

}

login.blade


<html>

<head>
    <title>Login</title>
</head>

<body>
<form method="POST" action="/auth/login">
    {!! csrf_field() !!}

    <div>
        Username
        <input type="text" name="username">
    </div>

    <div>
        Password
        <input type="password" name="password" id="password">
    </div>

    <div>
        <input type="checkbox" name="remember"> Remember Me
    </div>

    <div>
        <button type="submit">Login</button>
    </div>

</form>
</body>
</html>

routes.php

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('auth/login', 'Auth\AuthController@getLogin');
    Route::post('auth/login', 'Auth\AuthController@postLogin');
    Route::get('auth/logout', 'Auth\AuthController@getLogout');

LDAP Connection and Authentification is working when I use Adldap::auth() but I've had no luck in authenticating the user with Auth::attempt.

{{var_dump(Adldap::auth()->attempt('xxxx', 'xxxxx') )}} // true {{var_dump(Auth::attempt(['username' => 'xxxx', 'password' => 'xxxx']) )}} // false

Thanks a lot in advance.

stevebauman commented 7 years ago

Hi @handrej,

Is the user you're trying to authenticate located in the ou you're specifying here?:

'base_dn' => 'ou=xx,ou=xx,ou=xxxx,o=xxxx',
handrej commented 7 years ago

Yes, I'm using the same dn as account_suffix and base_dn for testing and I had no troubles authenticating / finding him directly through Adldap.

designvoid commented 7 years ago

Can confirm having exactly the same issue.

LDAP Connection and Authentification is working when I use Adldap::auth() but I've had no luck in authenticating the user with Auth::attempt.

{{var_dump(Adldap::auth()->attempt('xxxx', 'xxxxx') )}} // true {{var_dump(Auth::attempt(['username' => 'xxxx', 'password' => 'xxxx']) )}} // false

stevebauman commented 7 years ago

Hi @handrej, can you update to v3.0.* and try again? You're currently using v2.*.

stevebauman commented 7 years ago

@designvoid If you're having the same issue, and you're able to authenticate successfully directly against your server, then it's a configuration issue.

Are you able to dive into the source and dump & die (dd()), where it fails in the adldap auth driver?

designvoid commented 7 years ago

I have made a more detailed comment here: https://github.com/Adldap2/Adldap2-Laravel/issues/240

handrej commented 7 years ago

Hey @stevebauman, I recently started a fresh project with Laravel 5.4 and v3.0.*. Oddly enough I run into the same issue. On a short note, in refence to #240, im using no admin_username / admin_password for the admin account, since our LDAP allows anonymous access.

My configuration is mostly the same, and i followed your documentation on the Laravel 5.4 specifics changes in the auth.php. Might be an configuration issue, but I have no indicator on where it might fail.

Edit: He also finds the user running dd(Adldap::search()->where('cn', '=', 'x')->get())

On a sidenote, this LDAP is using SSL, if I activate use_ssl => true in the configuration and change the port, I can't establish a connection, if i leave it on false, it works.

stevebauman commented 7 years ago

On a sidenote, this LDAP is using SSL, if I activate use_ssl => true in the configuration and change the port, I can't establish a connection, if i leave it on false, it works.

Unfortunately I can't help troubleshoot connectivity issues.

All Adldap does with the use_ssl configuration is apply the ldaps:// prefix to your domain controller (here's essentially a stack trace):

https://github.com/Adldap2/Adldap2/blob/master/src/Connections/Provider.php#L251-L257

https://github.com/Adldap2/Adldap2/blob/master/src/Connections/Ldap.php#L82-L87

https://github.com/Adldap2/Adldap2/blob/master/src/Connections/Ldap.php#L424-L427

https://github.com/Adldap2/Adldap2/blob/master/src/Connections/Ldap.php#L210

And then you set the port in your configuration.

If no connectivity can be made, then it's most likely an issue on the web server or the domain controller.

He also finds the user running dd(Adldap::search()->where('cn', '=', 'x')->get())

Can you try Auth::attempt() and try dumping where it fails in the Adldap2-Laravel auth driver?

It would most likely fail here:

https://github.com/Adldap2/Adldap2-Laravel/blob/master/src/Auth/DatabaseUserProvider.php#L104-L105

Or here:

https://github.com/Adldap2/Adldap2-Laravel/blob/master/src/Auth/DatabaseUserProvider.php#L132

mzsolt1 commented 7 years ago

Hi,

I have a green project.

My project details: -Laravel 5.4 -PHP 5.6. -adldap2-laravel: 3.0.

I followed the instructions: https://github.com/Adldap2/Adldap2-Laravel/blob/master/docs/quick-start.md

but, I have two (three) problems.

1. If I use ADLAP auth, it works for me.

if (Adldap::auth()->attempt($username, $password)) { // Passed! } but $user = Auth::user(); always return null.

  1. php artisan adldap:import it works, but Found 0 user(s). why? if adldap:auth() work.. or i try this code $user = Adldap::search()->users()->find('Anything'); and results is null.

What Can I do? Please help me.

My files content:

adldap.php

    'default' => [

        'auto_connect' => true,
        'connection' => Adldap\Connections\Ldap::class,
        'schema' => Adldap\Schemas\ActiveDirectory::class,

        'connection_settings' => [

            'account_prefix' => env('ADLDAP_ACCOUNT_PREFIX', ''),
            'account_suffix' => env('ADLDAP_ACCOUNT_SUFFIX', '@something'),
            'domain_controllers' => explode(' ', env('ADLDAP_CONTROLLERS', 'company.org.corp')),
            'port' => env('ADLDAP_PORT', 389),
            'timeout' => env('ADLDAP_TIMEOUT', 5),
            'base_dn' => env('ADLDAP_BASEDN', 'DC=company,DC=org,DC=corp'),
            'admin_account_suffix' => env('ADLDAP_ADMIN_ACCOUNT_SUFFIX', ''),
            'admin_username' => env('ADLDAP_ADMIN_USERNAME', 'admin'), //yes, no password
            'admin_password' => env('ADLDAP_ADMIN_PASSWORD', ''),
            'follow_referrals' => false,
            'use_ssl' => false,
            'use_tls' => false,

        ],
    ],

adldap_auth:

'connection' => env('ADLDAP_CONNECTION', 'default'),
'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class,
'resolver' => Adldap\Laravel\Auth\Resolver::class,
'importer' => Adldap\Laravel\Auth\Importer::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' => [
    Adldap\Laravel\Scopes\UpnScope::class,
],

'usernames' => [
    'ldap' => 'samaccountname',
    'eloquent' => 'username',
],  
'login_fallback' => env('ADLDAP_LOGIN_FALLBACK', false),
'password_sync' => env('ADLDAP_PASSWORD_SYNC', true),
'windows_auth_attribute' => ['samaccountname' => 'AUTH_USER'],
'sync_attributes' => [

    'username' => 'samaccountname',
    'name' => 'cn',

],

auth.php

 'providers' => [
        'users' => [
            'driver' => 'adldap',
            'model' => App\User::class,
        ],

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Adldap\Laravel\Traits\HasLdapUser;

class User extends Authenticatable
{
    use Authenticatable, HasLdapUser;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'username', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

create_users_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('username')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Adldap\Laravel\Facades\Adldap;
use Auth;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function username()
    {
        return 'username';
    }

    /*
    public function login(Request $request)
    {
        try 
        {
            Adldap::connect();

            if (Adldap::auth()->attempt($request->input('username'), $request->input('password')))
            {

            }

        } catch (\Exception $e) {
            dd($e);
        }
    }*/

    /*
    public function login(Request $request)
    {
        if (Auth::attempt($request->only(['username', 'password']))) {

            // Returns \App\User model configured in `config/auth.php`.
            $user = Auth::user();

            dd($user);
            return redirect()->to('home')
                ->withMessage('Logged in!');
        }

        return redirect()->to('login')
            ->withMessage('Hmm... Your username or password is incorrect');
    }*/
}

UPDATE 03.29.

All things works for me, problem is wrong ADLDAP_ADMIN_USER and PASSWORD.