Why does custom guard get logged out on page reload/redirect?

218 views Asked by At

I created a new guard for logging in custom type of users. I can login users with Auth::attempt('webguest'), but login does not persist over page reloads. It works only when I use web-guard. See for example my two test routes:


Route::get('test1', function () {
    \Auth::guard('webguest')->attempt([ 
        'id' => 5,
        'password' => 2222
    ]);

    // here dump(\Auth::guard('webguest')->check()) shows true

    return \Redirect::to('/test2');
});

Route::get('test2', function () {
    return \Auth::guard('webguest')->check() ? "guest account logged in" : "guest not logged in";
   
   // dumps not logged in

});

My custom guard:

config/auth.php

'guards' => [

    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'webguest' => [
        'driver' => 'session',
        'provider' => 'guests'
    ],

],

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

    'guests' => [
        'driver' => 'eloquent',
        'model' => App\Models\Guest::class
    ],
]

Both Guest and User models extend Illuminate\Foundation\Auth\User as Authenticatable.

How can I make login with the custom guard persist like with web guard?

1

There are 1 answers

0
Alexandra Axt On BEST ANSWER

I've found the root cause. In my Guest model the "username" used for login is the id, and there was an overriden method in the model:

 public function getAuthIdentifier() {
            return $this->user->getKey();
 }

I removed it and added the following instead:

 public function getAuthIdentifierName()
    {
        return 'id';
    }

Now the custom guard works like a charm.