Laravel 8 使用 Guards Rest Password 的多重身份验证问题

Posted

技术标签:

【中文标题】Laravel 8 使用 Guards Rest Password 的多重身份验证问题【英文标题】:Laravel 8 Multi-authentication Using Guards Rest Password PROBLEM 【发布时间】:2021-06-25 16:17:27 【问题描述】:

我正在尝试使用守卫制作具有多重身份验证的 Laravel 应用程序。

Github: Repository

我创建了一个 Fresh Laravel 8 应用程序并添加了管理员守卫,现在我可以在管理员和用户模式下登录和注销。

此图片显示了我所做的详细信息,您可以跳过并阅读下面的管理员重置密码部分

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,

];

管理员重置密码部分

我给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');

然后我去了/admin/forget-password路由并提交了管理员电子邮件,但我收到以下错误:We can't find a user with that email address.

检查后我发现在PasswordResetLinkController 的函数store 中,它试图在users table/model 中查找管理员电子邮件。这是函数存储:

/**
 * 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)]);

如何强制 PasswordResetLinkController 和 NewPasswordController 类使用我添加到它们的 guard() 和 broker() 函数?

对不起,我试图在多个平台上搜索这个问题,他们只使用角色方法来做这个问题,如果我没有彻底解释,有些人可能不明白我在做什么

【问题讨论】:

您能分享一下您在 config/auth.php 中所做的更改吗? 当然可以,但是您可以获得完整的存储库,我将其附在问题中。 @Prospero 文件已添加 我做了一些相关但使用 Fortify 的事情。在 config/fortify.php 中,我配置了 Fortify 将使用的密码代理,这与 auth.php 中配置的多重重置密码有关。在您的文件中,这是在哪里制作的? laracasts.com/discuss/channels/laravel/… 这里是一些与微风有关的东西。看来你需要在这样的路由中使用中间件 Route::group(['middleware'=>'auth:admin'], function() // 管理员下的路由 ); 【参考方案1】:

重写代理函数:-

在您的PasswordResetLinkController.php 中,添加以下函数;
    /**
     * 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');
    
现在通过替换来更新PasswordResetLink.php 中的存储功能
    $status = Password::sendResetLink(
            $request->only('email')
        );

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

应该这样做!

【讨论】:

这一行抛出异常 => return Password::broker('admins'); ErrorException 未定义的数组键“过期” “过期”密钥从何而来?您可能遇到另一个错误,不是来自密码代理,而是相互关联。你能分享整个异常错误信息吗?【参考方案2】:

由于您使用的是 Laravel Breeze,请替换 PasswordResetLinkController.php 类的 store() 方法中的这行代码。

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

下面一行。

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

【讨论】:

【参考方案3】:

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

    ],

在 config/fortify.php 文件中

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

扩展 PasswordBrokerManager 类并重写代理方法,如

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]));
    

就我而言,我检查租户环境。您可以根据您的需要自定义您的,以供管理员或用户保护

【讨论】:

以上是关于Laravel 8 使用 Guards Rest Password 的多重身份验证问题的主要内容,如果未能解决你的问题,请参考以下文章

使用 Laravel Guards 登录后,如何限制用户不访问登录页面?

[PHP] 浅谈 Laravel Authentication 的 guards 与 providers

是否可以通过 [Web] Guard 使用 Laravel 资源?

Security Guards (Gym - 101954B)( bfs + 打表 )

[PHP] 自定义 laravel/passport 的误区讲解

身份验证用户提供程序 [passport] 未使用 laravel 护照定义