简体   繁体   中英

Laravel 5.3 Auth facade is changing to a default authenticated user

So I have a custom login flow in my laravel website. Ther users are located in an external data store that are accessible via an API. The flow is basically this. (minified)

public function login(Request $request) {
    $resultFromAPI = //call external API with email and password from $request
    if($resultFromAPI) {
        $user = User::find($resultFromAPI->user->user_id);
        if($user) { //user exists
             Auth::login($user);
             //dump( Auth::user() );
             return redirect('/');
        } else {
             $user = User::create([...]); //from $resultFromApi->user
             Auth::login($user);
             //dump( Auth::user() );
             return redirect('/');
        }
    }
}

If I try to login using user2@example.com , the dump will show that user's object. However, the second I'm redirected to / , Auth::user() will be user1@example.com My local db shows these two user records, but it's defaulting to the first user. I'm using the default logout function to logout and clear the sessions, and I've confirmed that Auth::user() is null when the logout function is called. I'm stuck.

EDIT: I tried Auth::attempt(...) instead of Auth::login(...) , it didn't change anything

EDIT2: I started from scratch using a clean installation of laravel 5.4, rewrote the login part to this

if ($this->attemptLogin($request)) {
  $request->session()->regenerate();
  $this->clearLoginAttempts($request);

  return $this->sendLoginResponse($request);
}

instead of this

Auth::login($user);
return redirect('/')

Still same issue

Finally solved the issue. My primary key was a custom uuid retrieved from my external api. I reverted the primary ley to be the default one ( $table->increments('id'); and it worked.

I looked it up , turns out I could've done public $incrementing = false; insided my User model and it would've stopped Laravel from thinking it's an incrementing field, and that might've solved it, but I haven't tested that.

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