2016-02-25 93 views
0

我試圖使用內置laravel 5.2的認證系統。如果我使用Auth :: check()替換return語句,則登錄似乎正常工作,它將返回true。但是當我重定向到'/'時,Auth :: check()在我的Auth中間件中突然返回false。Laravel 5.2,auth :: check在登錄後返回true,但在重定向後返回false

會話創建方法:

public function create(Request $request) 
{ 
    $email = $request->email; 
    $password = $request->password; 

    if(Auth::attempt(['email' => $email, 'password' => $password])) { 
     return redirect()->intended('/'); // returns true when replaced with Auth::check(); 
    } 

    return redirect("login"); 

} 

驗證中間件:

public function handle($request, Closure $next, $guard = null) 
{ 
    if (Auth::guest()) { 
     if ($request->ajax() || $request->wantsJson()) { 
      return response('Unauthorized.', 401); 
     } else { 
      return var_dump(Auth::check()); // returns false 
     } 
    } 

    return $next($request); 
} 

路線文件:

Route::post('/create-session', '[email protected]'); 
Route::get('/logout', '[email protected]'); 
Route::get('/login', function() { 
    return view('login'); 
}); 

Route::group(['middleware' => ['web', 'auth']], function(){ 
    Route::get('/', '[email protected]'); 
}); 
+0

您使用哪個會話驅動程序? – phaberest

+0

文件,但我也嘗試過Cookie – bim

+0

您在這些路線上使用了web和auth中間件嗎? – Ohgodwhy

回答

2

需要會話(這驗證使用)的所有路由必須具有「網'中間件應用。

另外:

Auth::check()正在於,只有當Auth::guest()是真正運行的代碼塊完成。 Auth::guest()Auth::check()的倒數。

所以你說的是你的中間件:如果當前用戶是一個guest(未驗證),檢查它們是否是一個經過驗證的用戶,在這一點上它總是假的。

更新:

根據您的意見:不要將身份驗證的中間件添加到「網絡」組。如果你這樣做,你將永遠無法擊中'網絡'路線,除非你在進行此更改之前進行了身份驗證。如果你這樣做,你甚至可以刪除能夠登錄的功能。

+0

現在已經修復了,我必須在所有登錄/註銷路由上應用web中間件,然後使用auth中間件來處理需要身份驗證的路由。 – bim

相關問題