不止一名警卫在路上

more than one guard in route

我使用 laravel 框架 我想在我的路线中使用多个守卫,例如:

   Route::group([ 'middleware' => 'jwt.auth', 'guard' => ['biker','customer','operator']], function () {}

我在 AuthServiceProvider.php 中有一个脚本,如下面的引导部分:

  $this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $event) {
        $route = $event->route;
        if (!array_has($route->getAction(), 'guard')) {
            return;
        }
        $routeGuard = array_get($route->getAction(), 'guard');
        $this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) {
            return $this->app['auth']->guard($routeGuard)->user();
        });
        $this->app['auth']->setDefaultDriver($routeGuard);
    });

在像 'guard'=>'biker'
这样的路线上只需要一名警卫就可以了 那么如何更改 AuthServiceProvider.php 中的代码以在路线

中使用多个 gaurd

我知道这是一个老问题,但我刚刚解决了这个问题并弄清楚了如何自己解决它。这可能对其他人有用。解决方案很简单,你只需要在你的中间件名称后面指定每个守卫,用逗号分隔,如下所示:

Route::group(['middleware' => ['auth:biker,customer,operator'], function() {
    // ...
});

然后将守卫发送到 \Illuminate\Auth\Middleware\Authenticate 函数 authenticate(array $guards),该函数检查数组中提供的每个守卫。

这适用于 Laravel 5.4。 也适用于 Laravel 6.0.