问题
I'm trying to use the authentication system that comes built in with laravel 5.2. The login seems to be working correctly, if I replace the return statement with Auth::check(), it returns true. But when I redirect to '/', Auth::check() suddenly returns false in my Auth middleware.
Sessions Create method:
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");
}
Auth Middleware:
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);
}
Routes file:
Route::post('/create-session', 'SessionController@create');
Route::get('/logout', 'SessionController@logout');
Route::get('/login', function() {
return view('login');
});
Route::group(['middleware' => ['web', 'auth']], function(){
Route::get('/', 'HomeController@getIndex');
});
回答1:
ALL routes that require sessions (which Auth uses) must have the 'web' middleware applied.
Also:
Your Auth::check() is being done in a code block that only runs if Auth::guest() is true. Auth::guest() is the inverse of Auth::check().
So you are saying in your middleware: If the current user is a guest (not authenticated), check if they are an authenticated user, which will always be false at this point.
Update:
Based on your comments: Do not add the authenticate middleware to the 'web' group. You will never be able to hit a 'web' route if you do this unless you were authenticated before you made this change. You are removing the ability to even be able to login if you do this.
来源:https://stackoverflow.com/questions/35633942/laravel-5-2-authcheck-return-true-after-login-but-false-after-redirect