Laravel Socialite: InvalidStateException
PhpFacebookLaravelLaravel 5Php Problem Overview
I'm using Laravel Socialite to add a Facebook connect button on a website. Sometimes, I've got this error on callback:
exception 'Laravel\Socialite\Two\InvalidStateException'
in /example/vendor/laravel/socialite/src/Two/AbstractProvider.php:161
I don't know what it mean and did not found anything yet about this error. The real problem is it seems to be a random exception (don't understood why it happens). So what this error means and how to avoid it?
It seems it's not the same problem as https://stackoverflow.com/questions/29629287/laravel-5-geting-invalidstateexception-in-abstractprovider-php, cause in my case it's random.
Php Solutions
Solution 1 - Php
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
- 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 bothwww.mysite.com
andmysite.com
Be sure to delete your cookies from browser when testing it after these modifications are done. Old cookies can still produce problems.
Solution 2 - Php
Resolved :
Socialite::driver('google')->stateless()->user()
Solution 3 - Php
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
Solution 4 - Php
There are 2 major "gotchas" that none of the existing answers address.
- 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. - 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 callshasInvalidState()
, 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.
Solution 5 - Php
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();
}
Solution 6 - Php
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
Solution 7 - Php
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.
Solution 8 - Php
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:
Solution 9 - Php
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'
).
Solution 10 - Php
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.
Solution 11 - Php
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());
}
Solution 12 - Php
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..
Solution 13 - Php
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;
}
Solution 14 - Php
I fixed this just disabling the SESSION DRIVER as database... file driver worked fine for me after hours trying to fix this s...
Solution 15 - Php
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.
Solution 16 - Php
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,
Solution 17 - Php
Finally i solved by :
Redirect URL in .env
file should be the same URL in google developer account
> double check on your redirects urls .
Solution 18 - Php
i have faced the same issue its just because of using 127.0.0.1:8000/ instead of http://localhost:8000/
Solution 19 - Php
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');
}
Solution 20 - Php
this solved it for me
$request->session()->put('state',Str::random(40)); $user = Socialite::driver('github')->stateless()->user();
Solution 21 - Php
On your Controller within the callback()
method
$user = $service->createOrGetUser(Socialite::driver('facebook')->user());
$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());
Solution 22 - Php
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.
Solution 23 - Php
I stacked on this two day and changing 'driver' => env('SESSION_DRIVER', 'file')
to 'driver' => env('SESSION_DRIVER', 'cookie')
worked for me
Solution 24 - Php
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.
Solution 25 - Php
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).
Solution 26 - Php
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
Solution 27 - Php
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;
}
// ...
}