DirectoryTree / LdapRecord-Laravel

Multi-domain LDAP Authentication & Management for Laravel.
https://ldaprecord.com/docs/laravel/v3
MIT License
508 stars 54 forks source link

[Question] Laravel 8 + own LDAP User Model + Auth = wrong Instance #316

Closed markusleitoldZBS closed 3 years ago

markusleitoldZBS commented 3 years ago

Environment (please complete the following information):

Describe the bug: In a fresh Laravel 8 App with enabled Vue UI including auth scaffolding (composer require laravel/ui; php artisan ui vue --auth) we want authenticate against our LDAP.

So we followd the docs here:

https://ldaprecord.com/docs/laravel/v2/installation https://ldaprecord.com/docs/laravel/v2/auth/plain/configuration https://ldaprecord.com/docs/laravel/v2/auth/plain/laravel-ui

As we neither use AD nor openLDAP or FreeIPA as LDAP Backend, we had to make our own LDAP User Model with:

php artisan make:ldap-model User

After entering valid credentials in the login Form and pressing "Login", this Laraval Exception occurs:

Argument 1 passed to LdapRecord\Laravel\Auth\NoDatabaseUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Ldap\User given, called in C:\git\laravel-tests\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php on line 415

This is the code: config/auth.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'ldap',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'ldap' => [
            'driver' => 'ldap',
            'model' => App\Ldap\User::class,
            'rules' => [],
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],
[...]

LoginController.php:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

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

    protected function credentials(Request $request)
    {
        return [
            'cn' => $request->username,
            'password' => $request->password,
        ];
    }
}

(As we authenticate with username instead of email, "cn" is used, where the username is stored in our LDAP)

App/Ldap/User.php:

<?php

namespace App\Ldap;

use LdapRecord\Models\Model;

class User extends Model
{
    /**
     * The object classes of the LDAP model.
     *
     * @var array
     */
    public static $objectClasses = [];
}

login.blade.php:

[...]
                        <div class="form-group row">
                            <label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>

                            <div class="col-md-6">
                                <input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>

                                @error('username')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
[...]

Any idea whats wrong here?

Thx in advance!

stevebauman commented 3 years ago

Hi @markusleitoldZBS,

Since you're using Plain LDAP authentication (no database synchronization) and your own custom model, you must implement Laravel's Authenticatable contract onto it, as well as its methods:

namespace App\Ldap;

use LdapRecord\Models\Model;
use Illuminate\Contracts\Auth\Authenticatable;

class User extends Model implements Authenticatable
{
    /**
     * The object classes of the LDAP model.
     *
     * @var array
     */
    public static $objectClasses = [];

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return 'the-auth-identifier-name';
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getFirstAttribute('the-auth-identifier');
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param string $value
     *
     * @return void
     */
    public function setRememberToken($value)
    {
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
    }
}

You can see the interface on the default Active Directory user model here:

https://github.com/DirectoryTree/LdapRecord/blob/master/src/Models/ActiveDirectory/User.php

And the methods added here:

https://github.com/DirectoryTree/LdapRecord/blob/master/src/Models/Concerns/CanAuthenticate.php

Since you're using some third party LDAP server I don't know about, you'll have to find out what the auth identifier's name and value should be. I cannot help you with that.

I'll keep this issue open while I add this into the documentation for future developers 👍

markusleitoldZBS commented 3 years ago

Hi @stevebauman,

thx a lot for the quick response and clearifying... I pasted your code example in our custom User Model (App/Ldap/User.php), replaced "the-auth-identifier-name" and "the-auth-identifier" with "cn" (as for us the "cn" attribute is unique for each user and I assume this has to be some sort of "primary Key" for the user, right?).

This almost was the solution, I just had to set this additionally in the user model:

protected $guidKey = 'cn';

So the working model now looks like this:

<?php

namespace App\Ldap;

use LdapRecord\Models\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use LdapRecord\Models\Concerns\CanAuthenticate;

class ATUser extends Model implements Authenticatable
{
    use CanAuthenticate;

    protected $guidKey = 'cn';

    /**
     * The object classes of the LDAP model.
     *
     * @var array
     */
    public static $objectClasses = [];

     /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return 'cn';
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getFirstAttribute('cn');
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param string $value
     *
     * @return void
     */
    public function setRememberToken($value)
    {
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
    }
}

Now everything works as expected :)

This is IMHO indeed worth being mentioned in the docs ;)

stevebauman commented 3 years ago

Completed: https://ldaprecord.com/docs/laravel/v2/auth/plain/configuration/#using-your-own-model