简体   繁体   中英

Laravel 5.1: Auth::attemp() success but Auth::check() return false

I already looking for related issue with this but didn't solved yet.

link 1 , link 2 , link 3

  • Auth::attempt() is success
  • try to register session after Auth::attempt() is success
  • remember_token field on users table is always null

This is my code:

AuthController:

protected function login(Request $request){
    $result = [];
    $rules = ['email' => 'required|email', 'password' => 'required|alphaNum|min:3'];
    $validator = Validator::make($request->all(), $rules);

    if($validator->fails()) {
        $result['message'] = 'Login Failed';

    }else{
        $userdata = ['email' => $request->email, 'password' => $request->password];
        if (Auth::attempt($userdata, $request->has('auth_remember'))) {
            // dd(Auth::user()); << THIS DATA IS EXIST
            // $request->session()->push('user.id', Auth::user()->id);
            // $request->session()->push('user.name', Auth::user()->name);
            // $request->session()->push('user.email', Auth::user()->email);

            // dd($request->session()->all()); << THIS DATA IS EXIST
            $result['message'] = 'Login successfull. Redirecting ...';
        }else{
            $result['message'] = 'User not found';
        }
    }
    echo json_encode($result);
}

I have a middleware Auth when I go to http://.../dashboard , but...

  • Auth::check() return false
  • $request->session()->has('user') return false

Auth Middleware:

    public function handle($request, Closure $next){
      if($this->auth->viaRemember()) return $next($request);

      if($this->auth->guest()){
        if($request->ajax()){
            return response('Unauthorized.', 401);
        }else{
            return redirect()->guest('login');
        }
      }

      return $next($request);
  }
  • storage/framework/session already set to 777
  • file session are generated
  • app timezone already match with server settings and database settings

Any help would be appreciated.

为什么要手动将记录的用户数据添加到会话中,您可以在尝试后随时使用Auth::user()获取用户数据

Delete this lines:

$request->session()->push('user.id', Auth::user()->id);
$request->session()->push('user.name', Auth::user()->name);
$request->session()->push('user.email', Auth::user()->email);

and verify with dd($request) the auth_remember

I think I resolve this issue.

Laravel authentication are not working when using Ajax. Just follow the documentation from http://laravel.com/docs/5.1/authentication and all should be worked!

But it's strange! Authentication with ajax are worked well in my localhost but no when I upload it to server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM