Search code examples
facebooklaravellaravel-socialite

Laravel Socialite with Facebook not logging in


I'm following the documentation exactly.

https://github.com/laravel/socialite and https://laravel.com/docs/5.1/authentication#social-authentication

I've created my app on Facebook and got everything working. When I click my log in with Facebook button, it authorizes the app and takes me back to my site. However, it doesn't show me as logged in. If I dd() instead of the redirect below, I get all of the data from my Facebook account. But the pages that are only visible to logged in users, aren't visible.

Here is my controller:

public function redirectToProvider()
{
    return Socialite::driver('facebook')->redirect();
}

public function handleProviderCallback()
{
    $user = Socialite::driver('facebook')->user();

    return redirect('my-profile')
            ->with('message', 'You have signed in with Facebook.');
}

Here are my routes:

Route::get('login/facebook', 'Auth\AuthController@redirectToProvider');
Route::get('login/facebook/callback', 'Auth\AuthController@handleProviderCallback');

Socialite is installed properly in composer.json. The classes are in config/app.php and the IDs for my FB app are in config/services.php.

Any ideas as to why it's not working?


Solution

  • In the handleProviderCallback method you need to create and authenticate the user returned by the driver.

    Create the user if doesn't exist:

    $userModel = User::firstOrNew(['email' => $user->getEmail()]);
    if (!$userModel->id) {
        $userModel->fill([.....]);
        $userModel->save();
    }
    

    Then authenticate the user:

    Auth::login($userModel);
    

    Your method will look like this:

    public function handleProviderCallback() {
        $user = Socialite::driver('facebook')->user();
    
        $userModel = User::firstOrNew(['email' => $user->getEmail()]);
        if (!$userModel->id) {
            $userModel->fill([.....]);//Fill the user model with your data
            $userModel->save();
        }
    
        Auth::login($userModel);
    
        return redirect('my-profile')
                ->with('message', 'You have signed in with Facebook.');
    }