简体   繁体   中英

Unable to successfully login using custom guard in Laravel

I am trying to create a new type of login that works alongside users table called business_users .

I have added the associated, tables, models and config into my auth.php files.

Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class BusinessUser extends Authenticatable
{
    protected $fillable = ['first_name', 'last_name', 'email', 'password', 'username'];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $guard = 'business_user';

    public function business()
    {
        return $this->belongsTo('App\Business');
    }

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

    public function getAuthPassword()
    {
        return $this->password;
    }

}

auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'business_user' => [
        'driver' => 'session',
        'provider' => 'business_users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],
...
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

     'business_users' => [
         'driver' => 'eloquent',
         'model' => App\BusinessUser::class,
     ],
],

Route (which fakes a login for testing)

Route::get('/business/fake-login', function () {

    $user = \App\BusinessUser::first();

    if (Auth::guard('business_user')->attempt(['username' => $user->username, 'password' => $user->password])) {
        return redirect()->intended('/business/dashboard');
    }

});

I am trying to use the business.username and business.password to login but the Auth:guard condition above returns false.

Can anyone explain what I'm doing wrong?

(fyi I am using Laravel 7.x)

You are retriving $user from the database, the password is encrypted.

Auth::attempt() will encrypt the password for you, so in the check password part, your password is actually being encrypted twice.

Instead, you may use Auth:attempt() like this:

$res = Auth::guard('business_guard')->attempt([
   'username' => "test",
   'password' => "test",
]);

dd( $res );

To understand further, you can go to EloquentUserProvider.php

public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];
    return $this->hasher->check($plain, $user->getAuthPassword());
}

Use you original code, and dd() the $plain to see what's going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM