Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF state token does not match one provided FB PHP SDK 3.1.1 Oauth 2.0

Tags:

My server logs show a "CSRF state token does not match one provided" error which seems to happen for almost every user. However, the users are created and/or authenticated and I am able to retrieve the user info. I am using a Linux server with Apache. I am also using the latest Facebook PHP SDK v.3.1.1 Can anyone tell me why this is happening and how to fix it?

like image 905
Harry Andrei Avatar asked Jan 23 '12 19:01

Harry Andrei


2 Answers

I had a similar issue last week, and tracked it down to the state field being overwritten by multiple calls to getLoginUrl(). Each time you call getLoginUrl(), a new state token is generated in the SDK and stored in the $_SESSION (it's just a random value), so if you call it twice and the user uses the first link to log in, the second call will have reset the SDK's internal state token, and you will get this error in your logs.

The SDK looks for the same state token in the URL coming back after Facebook authorizes the user and redirects them back to your site, and if it doesn't match it will log this error (here's a link to the source).

like image 83
jches Avatar answered Nov 07 '22 19:11

jches


Facebook SDK code has a bug when checking against tokens twice in the same handler.

I edited the getCode function of facebook.php like this:

protected function getCode() {     if (!isset($_REQUEST['code']) || !isset($_REQUEST['state']) || $this->state === null) {       return false;     }     if ($this->state === $_REQUEST['state']) {         // CSRF state has done its job, so clear it         $this->state = null;         $this->clearPersistentData('state');         return $_REQUEST['code'];     }     self::errorLog('CSRF state token does not match one provided.');      return false; } 

to be more clear and does not state invalid token if called twice.

To be clear the function can be called twice on the same url handler if eg:

$facebook->getUser(); and then in the same handler $facebook->getLogoutUrl() then the getCode() is called twice thus resulting into and invalid error message

like image 45
Jimmy Kane Avatar answered Nov 07 '22 18:11

Jimmy Kane