Laravel 5.2,auth :: check登录后返回true,但重定向后返回false [英] Laravel 5.2, auth::check return true after login but false after redirect

查看:228
本文介绍了Laravel 5.2,auth :: check登录后返回true,但重定向后返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用laravel 5.2内置的身份验证系统.登录名似乎正常运行,如果我用Auth :: check()替换return语句,它将返回true.但是当我重定向到"/"时,Auth :: check()在我的Auth中间件中突然返回false.

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.

会话创建方法:

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', 'SessionController@create');
Route::get('/logout', 'SessionController@logout');
Route::get('/login', function() {
   return view('login');
});

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

推荐答案

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

ALL routes that require sessions (which Auth uses) must have the 'web' middleware applied.

也:

您的Auth::check()是在仅在Auth::guest()为true的情况下运行的代码块中完成的. Auth::guest()Auth::check()的倒数.

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.

更新:

根据您的评论:不要将经过身份验证的中间件添加到"web"组.否则,您将永远无法打通网络"路线,除非您在进行此更改之前已通过身份验证.如果这样做,您甚至将无法登录.

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.

这篇关于Laravel 5.2,auth :: check登录后返回true,但重定向后返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆