Laravel Socialite: InvalidStateException

我正在使用 Laravel Socialite 在网站上添加一个 Facebook 连接按钮,有时候,我在回调时会出现这样的错误:

exception 'Laravel\Socialite\Two\InvalidStateException'
in /example/vendor/laravel/socialite/src/Two/AbstractProvider.php:161

我不知道这意味着什么,也没有发现任何关于这个错误。真正的问题是,这似乎是一个随机的例外(不明白为什么会发生这种情况)。那么这个错误意味着什么以及如何避免它呢?

看起来这和 Laravel 5在 AbstractProvider.php 中获得 InvalidStateException不是一个问题,因为在我的案例中它是随机的。

108724 次浏览

If you still need help you can use my code, it works for me. You just need to create two routes and update the users table. Don't forget to make password nullable, since you won't get one from the facebook users The code in my controller:

public function redirectToProvider()
{
return Socialize::with('facebook')->redirect();
}


public function handleProviderCallback(User $user)
{
$money = Socialize::with('facebook')->user();


if(User::where('email', '=', $money->email)->first()){
$checkUser = User::where('email', '=', $money->email)->first();
Auth::login($checkUser);
return redirect('home');
}


$user->facebook_id = $money->getId();
$user->name = $money->getName();
$user->email = $money->getEmail();
$user->avatar = $money->getAvatar();
$user->save();


Auth::login($user);
return redirect('home');


}

I ran into this issue last night and solve it with the following solution.

More information on my issue, I've got

InvalidStateException in AbstractProvider.php line 182

in the function handleProviderCallback() when it re-direct back from Facebook login. It seems to be the same as your issue.

Furthermore I found my issue occurs when I open my site without www. When I open my site with www.mysite.com - no problem. At first I think my issue is random until I've got the clue by Chris Townsend's reply to the question - Thank you very much.

The Solution

  1. Go to your www root, check the laravel file config/session.php
  2. Check session Session Cookie Domain The default configuration is 'domain' => null, I made a change to 'domain' => 'mysite.com'.
  3. After 'php artisan cache:clear' and 'composer dump-autoload', I can login with no issue from both www.mysite.com and mysite.com

Be sure to delete your cookies from browser when testing it after these modifications are done. Old cookies can still produce problems.

I fixed this just disabling the SESSION DRIVER as database... file driver worked fine for me after hours trying to fix this s...

Also check access right on your storage/framework/sessions folder.

In my case, since this folder is empty in new Laravel project, it has been left out during initially commit to the GIT repository. Afterwards I created it manually on production server, but obviously with the wrong access rights, hence it was not writable for the session driver (when set to 'file').

tl;dr

If you need to read a given parameter state returned by a thirdparty service, you can set Socialite to avoid this checking with the stateless method:

   Socialite::driver($provider)->stateless();

I think Socialite is already prepared to avoid this issue.

https://github.com/laravel/socialite/blob/2.0/src/Two/AbstractProvider.php#L77

 /**
* Indicates if the session state should be utilized.
*
* @var bool
*/
protected $stateless = false;

https://github.com/laravel/socialite/blob/2.0/src/Two/AbstractProvider.php#L374

/**
* Indicates that the provider should operate as stateless.
*
* @return $this
*/
public function stateless()
{
$this->stateless = true;
return $this;
}

https://github.com/laravel/socialite/blob/2.0/src/Two/AbstractProvider.php#L222

/**
* Determine if the current request / session has a mismatching "state".
*
* @return bool
*/
protected function hasInvalidState()
{
if ($this->isStateless()) {
return false; // <--------
}
$state = $this->request->getSession()->pull('state');
return ! (strlen($state) > 0 && $this->request->input('state') === $state);
}

For instance, state is very useful to pass data throught google:

Parameter: state (Any string)
Provides any state that might be useful to your application upon receipt of the response. The Google Authorization Server round-trips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, and cross-site-request-forgery mitigations.

ref: https://developers.google.com/identity/protocols/OAuth2UserAgent#overview

Resolved :

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

I want to share you my solution . I go to my AbstractProvider.php file and in the line of problem

public function user()
{
if ($this->hasInvalidState()) {
throw new InvalidStateException;
}


// ...
}

I stop the throw new InvalidStateException and call the redirect function like that:

public function user()
{
if ($this->hasInvalidState()) {
$this->redirect();
// throw new InvalidStateException;
}


// ...
}

I had the same problem and I just cleared the cache to solve this problem. I just ran this command and started the process again.

php artisan cache:clear

I hope this answer may help someone.

I was only experiencing this error when logging in via mobile web with the facebook app instead of facebook in browser. The facebook app uses the facebook browser after login instead of your current browser, so is unaware of previous state.

try {
$socialite = Socialite::driver($provider)->user();
} catch (InvalidStateException $e) {
$socialite = Socialite::driver($provider)->stateless()->user();
}

this solved it for me
$request->session()->put('state',Str::random(40)); $user = Socialite::driver('github')->stateless()->user();

I had a similar issue, I've got

InvalidStateException in AbstractProvider.php line 182

in the function handleProviderCallback() when it re-directs back from Facebook login. It seems to be the same as your issue.

Furthermore I found my issue occurs when I open my site without www. When I open my site with www.mysite.com - no problem. At first I think my issue is random until I've got the clue by Chris Townsend's reply to the question.

The Solution

Go to your www root, check the laravel file config/session.php. Check session Session Cookie Domain. The default configuration is 

'domain' => null,

I made a change to 

'domain' => 'mysite.com'

After php artisan cache:clear and composer dump-autoload, I can login with no issue from both www.mysite.com and mysite.com

Be sure to delete your cookies from browser when testing it after these modifications are done. Old cookies can still produce problems.

Got the Solution - Update November 2018

public function redirectToGoogle(Request $request)
{
/**
* @var GoogleProvider $googleDriver
*/
$googleDriver = Socialite::driver("google");
return $googleDriver->redirect();
}


public function fromGoogle(Request $request)
{
try {
/*
Solution Starts ----
*/
if (empty($_GET)) {
$t = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
parse_str($t, $output);
foreach ($output as $key => $value) {
$request->query->set($key, $value);
}
}
/*
Solution Ends ----
*/
/**
* @var GoogleProvider $googleDriver
*/
$googleDriver = Socialite::driver("google");
print_r($googleDriver->user());
} catch (\Exception $e) {
print_r($e->getMessage());
}

In my case it was caused by missing parameters in $fillable array in User class. When i added all missing parameters, it started to work properly..

There are 2 major "gotchas" that none of the existing answers address.

  1. Sometimes InvalidStateException is a red herring and the true root cause is some other bug. It took me ~12 hours one time to realize that I hadn't added a new field to the $fillable array in the model.
  2. Unless you disable session state verification (as other answers here seem to want you to do but not everyone will want to do), $provider->user() can only be called once per request because the inside of that function calls hasInvalidState(), which then removes the 'state' entry from the session. It took me hours to realize that I happened to be calling $provider->user() multiple times, when I should have called it just once and saved the result to a variable.

This issue has nothing to do with a lot of the solutions above, is rather as simple as changing your callback URL from 'http://localhost:8000/callback/twitter to http://127.0.0.1:8000/callback/twitter in your config/services.php and on your twitter app set up on your twitter application.

the http://localhost in the URL is the issue, replace with http://127.0.0.1

I've got same happen only when I open my web on mobile and open the dialog by facebook application on my phone.

I think: This happen because open facebook app to get response from Facebook API make we lost some cookie. it's become stateless. Then I just use the option that socialite are already made to avoid stateless request.

$user = Socialite::driver($provider)->stateless()->user();

It's worked to me. hope it help you

On your Controller within the callback() method

$user = $service->createOrGetUser(Socialite::driver('facebook')->user());

$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());

Laravel 6.16.0
php 7.4.2

I came across this exact issue. Turns out I recently changed same_site to strict and socialite was throwing InvalidStateException exception. Then I changed it to back to null and all worked fine.

/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict"
|
*/


'same_site' => null,

2020/04

If this issue appeared for you around Feb. 2020, there is a good chance it has to do with Google Chrome version 80+ which was released in the beginning of Feb. 2020. I am not going to pretend I understand the issue in it's entirety, but in short Google Chrome treats cookies now as SameSite=Lax by default if no SameSite attribute is specified.

If your app depends on working cross-site cookies, you will need to add "SameSite=None; Secure" to your cookies. In Laravel 5.5+ you can achieve that with two changes in the session configuration:

config/session.php

'secure' => env('SESSION_SECURE_COOKIE', true), // or set it to true in your .env file

...

'same_site' => "none",

The "none" value was apparently not supported in earlier Laravel versions. But it is now, if this produces a weird error check /vendor/symfony/http-foundation/Cookie.php and make sure there is a SAMESITE_NONE constant. If it doesn't exist you probably need to upgrade your Laravel version.

Further reading:

In my scenario, I had two Laravel applications running on localhost, one implementing passport, and on 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 lavarel_session cookie, so the socialite app wasn't able to pull the state value from the session, since the other app had stomped on the cookie.

Ensure that you set the APP_NAME value in .env when setting up your apps if you have them running on the same domain and are consuming your own provider.

Laravel: 7.10.3

PHP: 7.3.15

I was having this issue too. Somehow the proposed solutions didn't help me getting the problem fixed.

After spending a lot of time trying to fix my code, i thought this also could have to do something with my php-fpm -> nginx setup.

After changing my nginx configuration loging in via Facebook now works.

INCORRET CONFIGURATION:

location ~ \.(php|phar)(/.*)?$ {
fastcgi_split_path_info ^(.+\.(?:php|phar))(/.*)$;
fastcgi_intercept_errors on;
fastcgi_index  index.php;
include        fastcgi_params;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
fastcgi_param  PATH_INFO $fastcgi_path_info;
fastcgi_pass   unix:/var/run/php-fpm/www.sock;
}


location / {
try_files $uri $uri/ /index.php;
}

CORRECT CONFIGURATION

location / {
try_files $uri $uri/ /index.php?$query_string;
}


location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

I stacked on this two day and changing 'driver' => env('SESSION_DRIVER', 'file')to 'driver' => env('SESSION_DRIVER', 'cookie') worked for me

For me the solution was to set APP_URL to http://localhost:8000 instead of http://127.0.0.1:8000 (presuming that you run your server on the 8000 port).

Then, clean config and cache:

  • php artisan config:clear
  • php artisan cache:clear

Clear cookies (or run in incognito mode)

Since facebook allow localhost redirect by default, you don't have to whitelist the url in the fb app.

October 2020

For me, I had

…\vendor\laravel\socialite\src\Two\AbstractProvider.php209

So I converted my code from

$user = Socialite::driver('facebook')->user();

to

$user = Socialite::driver('facebook')->stateless()->user();

I didn't have to run any cache clearing, I did delete the cookies though but I'm not sure you have to.

Finally i solved by :

Redirect URL in .env file should be the same URL in google developer account

double check on your redirects urls .

i have faced the same issue its just because of using 127.0.0.1:8000/ instead of http://localhost:8000/

This is a session-related issue.

If you're using an SSH tunneling service such as ngrok.com then you should use the exact same URL as the social redirect URL, otherwise, you need to modify the domain in the session.php file (which is a bad idea IMO).