Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

php - Laravel 5.2, auth::check return true after login but false after redirect

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');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...