如何对同一控制器使用laravel多重身份验证保护


How to use laravel Multiple Auth Guard for same controller

laravel 5.2

我在下面给出了多个授权Gard

管理客户端受雇者

我有

    
ItemController
        ->index.blade.php
        ->create.blade.php
        ->edit.blade.php
ItemKitController
        ->index.blade.php
        ->create.blade.php
        ->edit.blade.php

我想使用客户端和员工保护来访问相同的控制器并查看上面提到的内容。

是他们任何可能的方式。

也许你想要这样的

public function __construct()
    {
        $this->middleware('auth:Admin,Clients,Employee');
    }

在您的控制器中

您可以使用中间件,如:

Route::group([ 'middleware' => ['Admin', 'Clients', 'Employee'] ], function(){
  Route::get('/Admin', 'AdminController@index');
  Route::get('/Clients', 'ClientsController@index');
  Route::get('/Employee', 'EmployeeController@index');
});

例如,我有一个管理中间件,它检查用户id是否为1

<?php
namespace App'Http'Middleware;
use Closure;
use Auth;
use Log;
class AuthAdmin
{
    private $admins; // Admin ids
    /**
     * Handle an incoming request.
     *
     * @param  'Illuminate'Http'Request  $request
     * @param  'Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->admins = config('custom.admins'); // get configs
        $user = Auth::user();
        if($user->id != 1)){
            // not admin, redirect home
            return redirect('/');
        }
      // is admin, let request continue
      return $next($request);
    }
}

然后您必须将其添加到Kernel.php"$routeMiddleware":

protected $routeMiddleware = [
        'auth' => 'App'Http'Middleware'Authenticate::class,
        'auth.basic' => 'Illuminate'Auth'Middleware'AuthenticateWithBasicAuth::class,
        'can' => 'Illuminate'Foundation'Http'Middleware'Authorize::class,
        'guest' => 'App'Http'Middleware'RedirectIfAuthenticated::class,
        'throttle' => 'Illuminate'Routing'Middleware'ThrottleRequests::class,
        // Custom Middleware
        // Auth Admin
        'auth_admin' => 'App'Http'Middleware'AuthAdmin::class,
    ];

然后在我的路线上:

Route::group([ 'middleware' => ['auth_admin'] ], function(){
    // nobody can come to these routes but admins
    Route::get('/admin/index', 'AdminController@index');
});