php 如何使用Laravel 8的基本.auth中间件允许来自2个不同auth guards的用户访问?

sy5wg1nm  于 2023-05-27  发布在  PHP
关注(0)|答案(1)|浏览(116)

我在Laravel 8中有一个模块,我想允许来自2个不同的auth guards的用户访问。为了定义访问,我在模块Controller中使用中间件:

public function __construct()
{
    $this->middleware('auth.basic:web');
    $this->middleware('auth.basic:cust');
}

如图所示,我使用了basic.auth和两个不同的guards:网站和客户身份验证防护在整个系统中工作,并且配置正确。
如何在基本身份验证中进行多重保护身份验证?我尝试了很多东西,但我stucket...请帮助
我尝试了不同的语法:$this->middleware(['auth.basic:web','auth.basic:cust']);自定义中间件也尝试获取返回结果是auth成功:

public function handle($request, Closure $next)
{
    $this->auth->guard('web')->basic('email');
   
    if( ! $this->auth->guard('web')->id()) {
        $this->auth->guard('cust')->basic('email');
    }

    return $next($request);
}
toiithl6

toiithl61#

你说你使用基本的认证和2个不同的警卫:网站和客户但是默认的laravel auth使用web guard。我假设您正在中间件中尝试if条件。如果是这种情况,那么在$routeMiddleware数组中注册您的中间件。
请按以下方式尝试:

if ($this->auth->guard($guard)->check()) 
{
     $this->auth->shouldUse($guard);

     return $this->auth->authenticate();
}

然后在路线中你可以做:

Route::middleware('multi.auth')->group(function () {
    // Routes accessible by users from both guards
});

另外,请确保在config/auth.php文件中正确配置了防护。它们应该如下所示:

'guards' => [
'guard1' => [
    'driver' => 'session',
    'provider' => 'provider1',
],

'guard2' => [
    'driver' => 'session',
    'provider' => 'provider2',
    ],
],

请让我知道它是否有效。谢谢!

相关问题