Weird Facebook API - Facebook PHP-SDK behavior. CSRF state token does not match one provided

Nishant Arora 14/Oct/2012
Facebook
Twitter
LinkedIn
Reddit

I checked again and again with Devs facing a similar issue with Facebook API. The PHP-SDK logs an error on every run that says

CSRF state token does not match one provided.
<code>
</code>

The weird thing is, the intended application seems to work fine (It's a batch posting script and as soon as I reset the batch, it generates this error.)

So I tracked down to base_facebook.php in the PHP-SDK providedĀ here. and changed this code (inĀ here):

protected function getCode() {
    if (isset($_REQUEST['code'])) {
      if ($this->state !== null &amp;&amp;
          isset($_REQUEST['state']) &amp;&amp;
          $this->state === $_REQUEST['state']) {

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

to this one (just to track errors in the error log):

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

    return false;
  }
<code>
</code>

On running the app again, I get the updated error to:

CSRF state token does not match one provided. state is null. states do not match.
<code>
</code>

now, $this->state() is NULL, I did not expect this to be the least of the errors in facebook sdk. I'm sure my app only generates one login url request, that too only if the user has no session with my app.

Help will be appreciated. Read the SO question here

PS: you can workaround this problem by commenting out:

$this->state = null;
$this->clearPersistentData('state');