簡體   English   中英

中間件中的多個身份驗證。 Laravel 5.4

[英]Multiple auth in middleware. Laravel 5.4

我是PHP和Laravel的新手。 我嘗試在線搜索,但無法為我的問題找到正確的答案。 我希望只有經過身份驗證的管理員和用戶才能訪問我的特定頁面。 因此,基本上,所有用戶都需要先登錄。 這是我的代碼。 提前致謝。

HomeController.php

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:web, auth:admin');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('accounts.user.user_dashboard');
    }
}

auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],

我在路由文件中使用了這個

Route::group(['middleware' => ['auth']], function (){
     Route::get('/dashboard', 'HomeController@index'); 
}

您可以創建一個中間件來檢查用戶是否具有一定的權限。 這是我習慣的方式。

我創建了一個中間件,例如說SuperAccess,並在那里寫我的超級管理員邏輯。

class SuperAccess
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);
    if(Auth::check() && Auth::user()->role->permission == 1000){
        return redirect('web/dashboard');
    }
    return $response;
}
}

然后我在需要檢查superAccess的地方使用中間件,例如在DeviceController中說

class DevicesController extends Controller
{
public function __construct(){
    $this->middleware('auth');
    $this->middleware('super');
}

注意:在上面的示例中,我有一個角色表,該表與用戶表有關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM