mrkarma4ya's avatar

Socialite - Facebook: Missing Authorization Code

I implemented login with facebook in my website using Laravel Socialite, and its working as expected. My colleagues have tested it as well.

However, there are a few errors in my log file with this message:

[2021-09-20 07:09:55] production.ERROR: Client error: `POST https://graph.facebook.com/v3.3/oauth/access_token` resulted in a `400 Bad Request` response:
{"error":{"message":"Missing authorization code","type":"OAuthException","code":1,"fbtrace_id":"[xxxxxxx]" (truncated...)
 {"exception":"[object] (GuzzleHttp\Exception\ClientException(code: 400): Client error: `POST https://graph.facebook.com/v3.3/oauth/access_token` resulted in a `400 Bad Request` response:
{\"error\":{\"message\":\"Missing authorization code\",\"type\":\"OAuthException\",\"code\":1,\"fbtrace_id\":\"[xxxxxxx]\" (truncated...)
 at /var/www/app.sajilocv.com/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113)

I've been trying to figure out what's happening, but I can't recreate the issue. What do I do in these situations?

0 likes
4 replies
Wakanda's avatar

@mrkarma4ya

Facebook returned a 400 because they could not validate your app secret. As outlined in the Socialite configuration documentation, you need to add your Facebook configuration in config/services.php.

I use something like this and set the values in the .env file:

'facebook' => [
    'client_id' => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect' => env('FACEBOOK_REDIRECT_URI')
],

NB: make sure you insert correct production variables that are associated with your production domain

mrkarma4ya's avatar

@Wakanda I have set all these, and when I try, I can log in without any problem. But according to the logs, some users are getting this issue, and I don't know what to do.

Wakanda's avatar

@mrkarma4ya

Did you change from development to live on your Facebook app settings?

You may also want to handle a case when a user does not use an email on Facebook but uses a phone number instead

anilkumarthakur60's avatar
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CLIENT_REDIRECT=http:

and all your social client_id,secret,rediret define in .env file

Route::get('login/{driver}', 'Auth\LoginController@redirectToProvider')->name('social.oauth');
Route::get('login/{driver}/callback', 'Auth\LoginController@handleProviderCallback')->name('social.callback');

login.blade.php

 <form method="POST" action="{{ route('login') }}">
                    @csrf
.
..
...
  <a href="{{ route('social.oauth','github') }}" class="btn btn-info"> Github</a>
 <a href="{{ route('social.oauth','facebook') }}" class="btn btn-info">facebook </a>
<a href="{{ route('social.oauth','twitter') }}" class="btn btn-info"> twitter</a>
<a href="{{ route('social.oauth','google') }}" class="btn btn-info"> google</a>
 </form>
protected $providers = [ 'github','facebook','google','twitter' ];

public function redirectToProvider($driver)
{
    if( ! $this->isProviderAllowed($driver) ) {
        return $this->sendFailedResponse("{$driver} is not currently supported");
    }

    try {
        return Socialite::driver($driver)->redirect();
    } catch (Exception $e) {
        // You should show something simple fail message
        return $this->sendFailedResponse($e->getMessage());
    }
}


public function handleProviderCallback( $driver )
{
    try {
        $user = Socialite::driver($driver)->user();
    } catch (Exception $e) {
        return $this->sendFailedResponse($e->getMessage());
    }

    // check for email in returned user
    return empty( $user->email )
        ? $this->sendFailedResponse("No email id returned from {$driver} provider.")
        : $this->loginOrCreateAccount($user, $driver);
}

protected function sendSuccessResponse()
{
  
     return redirect()->intended($this->redirectTo());





}

protected function sendFailedResponse($msg = null)
{
    toastr()->warning('Unable to login, try with another provider to login.');
    return redirect()->route('login')
        ->withErrors(['msg' => $msg ?: 'Unable to login, try with another provider to login.']);
}

protected function loginOrCreateAccount($providerUser, $driver)
{
    // check for already has account
    $user = User::where('email', $providerUser->getEmail())->first();

    // if user already found
    if( $user ) {
        // update the avatar and provider that might have changed
        $user->update([
            'avatar' => $providerUser->avatar,
            'provider' => $driver,
            'provider_id' => $providerUser->id,
            'access_token' => $providerUser->token,

        ]);
    } else {
        // create a new user
        $user = User::create([
            'name' => $providerUser->getName(),
            'email' => $providerUser->getEmail(),
            'avatar' => $providerUser->getAvatar(),
            'provider' => $driver,
            'provider_id' => $providerUser->getId(),
            'access_token' => $providerUser->token,
            'email_verified_at' => now(),
            // user can use reset password to create a password
            'password' => ''
        ]);
    }

    // login the user
    Auth::login($user, true);

    return $this->sendSuccessResponse();
}

private function isProviderAllowed($driver)
{
    return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}

Please or to participate in this conversation.