Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

leolam2005's avatar

I found the problem and solution, and,

You shouldn't do that...

        $state = $request->get('state');
           $request->session()->put('state',$state);

        if(\Auth::check()==false){
          session()->regenerate();
        }

Because it seems that the state checking is to ensure user is not hack you by input,

You are just skipping the checking...

Instead, I

'domain' = env('DOMAIN', null), //config/session.php
DOMAIN=mysite.dev  //.env
DOMAIN=mysite.com //.env production
// change the .env session driver to Redis (Optional)
// clear my browser's cookies

when I die dump the $state (session) and request state,

I found that the session $state is null, just because the session problem.

Other session problem might be that You are using file session but no write permission, thus null $state session.

2 likes
alexmansour's avatar

Hello @leolam2005 I'm already having the domain set and the used session driver is Redis but the issue occurs sometimes with some users.

Any ideas what could be the issue?

Thanks.

sieabah's avatar

To anyone who is still having this problem it may be due to caching of query strings or query strings not being forwarded along (cloudflare/cloudfront). Make sure to forward the query string and don't strip it off between the browser and the server.

Yefferson's avatar

I think that happens only when the user rejects the app. If that's the case, It should help:

     /**
     * Redirect the user to the Facebook authentication page.
     *
     * @return Response
     */
    public function redirectToProvider(){
        return Socialite::driver('facebook')->redirect();
    }

    /**
     * Obtain the user information from Facebook.
     *
     * @return Response
     */
    public function handleProviderCallback(){
        try{
            $user = Socialite::driver('facebook')->user();
        } catch (\Exception $e) {
            return redirect('/login')->with('status', 'Something went wrong or You have rejected the app!');
        }

        $authUser = $this->findOrCreateUser($user);

        Auth::login($authUser, true);

        return redirect()->route('home');
    }

    /**
     * Return user if exists; create and return if doesn't
     *
     * @param $facebookUser
     * @return User
     */
    private function findOrCreateUser($facebookUser)
    {
        $authUser = User::where('facebook_id', $facebookUser->id)->first();

        if ($authUser) {
          return $authUser;
        }

        return User::create([
            'name' => $facebookUser->name,
            'email' => $facebookUser->email,
            'facebook_id' => $facebookUser->id,
            'avatar' => $facebookUser->avatar
        ]);
    }

Off course you'll need in the migration to include the facebook_id

$table->string('facebook_id')->unique()->nullable();

and also put it as mass asignable in the User model.

brakkar's avatar

I had this error because I was accessing my local site from the local ip instead of localhost. You should use localhost if that was is set on facebook as authorized url.

1 like
Alkimisti's avatar

This problem has nothing to do with sessions, it has to do with callback URL the moment that Facebook redirects to your site after authentication.

If in .env you use FACEBOOK_URL with www like so FACEBOOK_URL=http://www.example.com/login/facebook/callback, your site visitor should open your site with www like so http://www.example.com/ prior to clicking the Login button. Same logic applies for FACEBOOK_URL without www.

Thus, you may add to .htaccess the following lines:

RewriteCond %{HTTP_HOST} ^example.com [NC]

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Now, when visitor enters http://example.com, .htaccess will redirect him to http://www.example.com. In .env use URL with www and everything will be just fine.

2 likes
uscbsitric's avatar

In my case i was using facebook, i tried to logout in facebook, and i tried my redirect URL again and it prompted me to login via facebook using my facebook credentials and then all my custom logic kicks in and I dont encounter that error again.

To see that error immediately, in my case i just had to invoke the url that facebook gave as a redirect/response right after Login via facebook. So I think that it has something to do with our being logged-in in facebook, and kinda like behind the scenes sending an invalid access token of sort.

santosh.1993's avatar

Hi, I was just tried this below code and it works for me.

try{ $socialUser = Socialite::driver('facebook')->user(); } catch(\Exception $e){ return redirect('/'); }

return $socialUser->getEmail();

eldin's avatar

I had the same error, and I added this at the top of the controller method which I used to handle request:

session()->put('state', $request->input('state'));
session()->put('code', $request->input('code'));

End it worked,...

absmendoza's avatar

Sooo... I used Socialite for Google authentication and it works in my localhost. But when I deployed it to production, it didn't work. I got the error: Client error: POST https://accounts.google.com/o/oauth2/token resulted in a 400 Bad Request response: { "error" : "invalid_request", "error_description" : "Missing required parameter: code" }

Meaning it can't get the access token/rights to Google, it's this line: $socialUser = Socialite::driver($provider)->user();

I still don't know how to fix it. Has anybody used Laravel Socialite in their production server?

zinmyo's avatar

I have same problem of this

Laravel\Socialite\Two\InvalidStateException 
…\vendor\laravel\socialite\src\Two\AbstractProvider.php210
viglucci's avatar

In my scenario, I had two Laravel applications running on localhost, one implementing passport, and one utilizing socialite to authenticate against the passport application. I had forgotten to set the APP_NAME in .env, so each application was writing the same laravel_session cookie. This caused the socialite app to be unable to pull the state value from the session since the other app had stomped on and rewritten the cookie.

1 like
omnia89's avatar

@viglucci Thanks!! I had the same problem in the same scenario, it drived me crazy for 2 days!!

I feel very stupid right now..

christiantomax's avatar

in my scenario, this step fixed Laravel error Laravel\Socialite\Two\InvalidStateException. just comment the $scopes array in \laravel\socialite\src\Two\GoogleProvider.php like this : protected $scopes = [ 'openid', //'profile', 'email', ];

Previous

Please or to participate in this conversation.