如何在 laravel 中指定多个经过身份验证的警卫

how to specify more than one authenticated guard in laravel

我正在阅读 laravel 网站的身份验证部分 https://laravel.com/docs/5.2/authentication

任何人都可以解释我如何做到这一点,就像文档解释的那样,指定单独的表进行身份验证...我将引用 laravel 的内容,如下所示:

Accessing Specific Guard Instances

You may specify which guard instance you would like to utilize using the guard method on the Auth facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

if (Auth::guard('admin')->attempt($credentials)) {
    //
}

你还得看一下添加自定义守卫和提供者的例子,主要是配置部分。您可以使用相同的 auth 'driver',您只是想调整 Auth 用户提供程序使用的模型。

config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    // add another one
    // use the same driver, 'session', but a different user provider
    'admin' => [
         'driver' => 'session',
         'provider' => 'admins',
     ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    // add a provider using Eloquent but using a different model
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
]

那你应该可以指定守卫admin来Auth了。只要 Admin 模型实现了 Authenticatable 并且您将适当的凭据传递给 Auth 上的 attempt,您应该是好的。

如果你有更多的中间件并且你想应用不止一个守卫,我的意思是中间件你可以在任何 Middleware.php 文件中执行此操作:

public function handle($request, Closure $next)
{
    // if a user is Agency or Admin, let him through
    if (Auth::user()->isAgency() || Auth::user()->isAdmin()) {
        return $next($request);
    } 
    // else show error page
    abort(403);
}