Laravel 5.2,auth :: check在登录后返回true,但在重定向后返回false

时间:2016-02-25 17:15:40

标签: php authentication laravel-5.2 laravel-middleware

我正在尝试使用laravel 5.2内置的身份验证系统。登录似乎工作正常,如果我用Auth :: check()替换return语句,它返回true。但是当我重定向到'/'时,Auth :: check()突然在我的Auth中间件中返回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");

}

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);
}

路由文件:

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 个答案:

答案 0 :(得分:2)

需要会话的所有路由(Auth使用的路由)必须应用' web' 中间件。

此外:

您的Auth::check()正在代码块中完成,该代码块仅在Auth::guest()为真时运行。 Auth::guest()Auth::check()的倒数。

所以你在中间件中说:如果当前用户是访客(未经过身份验证),请检查他们是否是经过身份验证的用户,此时此用户始终为false。

更新

根据您的评论:不要将经过身份验证的中间件添加到' web'组。你永远无法打到一个网络'路由,如果您这样做,除非您在进行此更改之前进行了身份验证。如果你这样做,你甚至无法登录。