this is the code I am using for a side project in PROD. so far working without any problem.
I hope it helps you to get this tricky thing done :D, as you can see it is easier than what it looks.
The error might be the way you're setting up your routes to handle the Auth and the Callback, for me it seems that you have the same route for both and that way when Facebook approves and sends the user back, your website redirects again to the OAuth endpoint and so on.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Response;
use Laravel\Socialite\Facades\Socialite;
class LoginController extends Controller
{
/**
* Redirect the user to the GitHub authentication page.
*
* @param $provider
* @return Response
*/
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* @param $provider
* @return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
auth()->login($authUser, true);
return redirect('/home');
}
/**
* Finds or creates an user.
*
* @param $user
* @param $provider
* @return mixed
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id,
]);
}
}
And this is how we have our services set up (instead of the env, you can also use the route function).
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'twitter' => [
'client_id' => env('TWITTER_CLIENT_ID', ''),
'client_secret' => env('TWITTER_CLIENT_SECRET', ''),
'redirect' => env('APP_URL', '').'/auth/twitter/callback',
],
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID', ''),
'client_secret' => env('FACEBOOK_CLIENT_SECRET', ''),
'redirect' => env('APP_URL', '').'/auth/facebook/callback',
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID', ''),
'client_secret' => env('GOOGLE_CLIENT_SECRET', ''),
'redirect' => env('APP_URL', '').'/auth/google/callback',
],
];
//Routes for socialite
Route::get('auth/{provider}', 'LoginController@redirectToProvider');
Route::get('auth/{provider}/callback', 'LoginController@handleProviderCallback');
auth/facebook
again, trying to trigger the whole auth process again. Remove that redirect, and instead check what the exception actually has to say at this point- – 04FS