Search code examples
laravel-5google-oauthphp-7.2laravel-socialite

Error Laravel\Socialite\Two\InvalidStateException In the callback method from the Google side


I want use Socialite package but receive in Error !

controller codes :

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;

class GoogleAuthController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callback()
    {
        // when i dd() here i see in the answer in the browser.
        $googleUser = Socialite::driver('google')->user();
        // but dd in here isn't working!
       
        $user = User::where('email', $googleUser->email)->first;

        if ($user) {
            auth()->loginUsingId($user->id);
        } else {
            $newUser = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => bcrypt(\Str::random(16)),
            ]);
            auth()->loginUsingId($newUser->id);
        }
        return $this->redirect('/');
    }
}

in web.php :

Route::get('auth/google', 'Auth\GoogleAuthController@redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController@callback');

laravel version : 6.20.26

php version : 7.2.5

please help me. tnks

===============================================================

I try this (https://stackoverflow.com/a/37849202/20355717) :

Socialite::driver('google')->stateless()->user()

but in did't work for me and give error ! :

GuzzleHttp\Exception\RequestException

cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token


http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W 


Solution

  • 1- change :

    Socialite::driver('google')->user()
    

    to in :

    Socialite::driver('google')->stateless()->user()
    

    2- download cacert.pem add this code in php.ini file.

    curl.cainfo = "D:\wamp64\bin\php\php7.4.26\cacert.pem
    

    like this https://stackoverflow.com/a/40861755/20355717

    3- change

    return $this->redirect('/');
    

    in controller to

    return view('welcome'); //or an any other view.
    

    4- finish! hope helpful for you!