Laravel 8 Multi-authentication Using Guards Rest Password PROBLEM


I am trying to make a Laravel App with multi-authentication using guards.

Github: Repository

I created a Fresh Laravel 8 App and added admin guard and now I am able to login and logout in both admin and user modes.

This Picture Shows the details of what I did you can skip and just read Admin reset password section below
Laravel 8 Multi-authentication Using Guards Rest Password PROBLEM

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' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        '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,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

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

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],

        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 30,
            'throttle' => 30,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

Admin Reset Password Section

I added the flowing functions to PasswordResetLinkController and NewPasswordController for admin:

/**
 * Get the guard to be used during authentication.
 *
 * @return \Illuminate\Contracts\Auth\StatefulGuard
 */
protected function guard()
{
    return Auth::guard('admin');
}

/**
 * Returns the password broker for admins
 * 
 * @return broker
 */
protected function broker()
{
    return Password::broker('admins');
}

And then I went to /admin/forget-password route and submitted the admin email but I got the following error: We can't find a user with that email address.

After checking I found that in the function store of the PasswordResetLinkController it is attempting to find an admin email in the users table/model. Here is function store:

/**
 * Handle an incoming password reset link request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse
 *
 * @throws \Illuminate\Validation\ValidationException
 */
public function store(Request $request)
{
    $request->validate([
        'email' => 'required|email',
    ]);

    // We will send the password reset link to this user. Once we have attempted
    // to send the link, we will examine the response then see the message we
    // need to show to the user. Finally, we'll send out a proper response.
    $status = Password::sendResetLink(
        $request->only('email')
    );

    return $status == Password::RESET_LINK_SENT
                ? back()->with('status', __($status))
                : back()->withInput($request->only('email'))
                        ->withErrors(['email' => __($status)]);
}

How can I force classes PasswordResetLinkController and NewPasswordController to use guard() and broker() functions I added to them?

Sorry for the long explanation I tried to search for this question on multiple platforms they are only using the roles approach to do it, if I didn’t explain thoroughly some might not understand what I am trying to do

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Since you are using Laravel Breeze, replace this line of code in the store() method of the PasswordResetLinkController.php class.

$status = Password::sendResetLink($request->only('email'));

With the following line.

Password::broker('admins')->sendResetLink($request->only('email'))

Solution 2

In config/auth.php

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

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

        'tenant' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\User::class,
        ],
    ],
///
'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
        'tenant' => [
            'provider' => 'tenant',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],

    ],

In the config/fortify.php file

    'passwords' => ['users','tenant'],

extend the PasswordBrokerManager class and override the broker method like

public function broker($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();
        if (Tenancy::getTenant()) {
            return $this->brokers[$name[1]] ?? ($this->brokers[$name[1]] = $this->resolve($name[1]));
        }
        else
            return $this->brokers[$name[0]] ?? ($this->brokers[$name[0]] = $this->resolve($name[0]));
    }

In my case, I check for tenant environment. You can customize your by your needless, in your case for admin or user guard

Solution 3

Override the broker function :-

  • in your PasswordResetLinkController.php, add the following function;
    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker(): \Illuminate\Contracts\Auth\PasswordBroker
    {
        return Password::broker('admins');
    }
  • Now update the store function in PasswordResetLink.php by replacing
    $status = Password::sendResetLink(
            $request->only('email')
        );

to

    $status = $this->broker()->sendResetLink(
            $request->only('email')
        );

That should do it!

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply