I am trying to set up login with Google using Laravel and socialite. I've set everything up to go to the Google login page and redirect me back to the application. However, when I'm redirected I always end up on the "login" page and not the "home" page. After successfully logging in with Google I'm not logged into my Laravel app. What is wrong?
/**
* Obtain the user information from Google.
*
* @return \Illuminate\Http\Response
*/
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->name;
$newUser->email = $user->email;
$newUser->google_id = $user->id;
$newUser->avatar = $user->avatar;
$newUser->avatar_original = $user->avatar_original;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->to('/home');
}
Despite the calls to login a user I am not logged in when redirected back to the app. How can I make sure that after logging in with Google I'm logged in to the Laravel app?
Update
It turns out when the $user variable comes back from Google I am getting a InvalidStateException
The try catch block actually throws an exception. If I dd the exception it looks like:
It turns out what was breaking it for me was in my .env file I had:
SESSION_DOMAIN=http://localhost:8000
Removing this line fixed the issue!
Remove SESSION_DOMAIN
from your .env file