Facebook PHP SDK - getLoginUrl() - state value

csrf, facebook, facebook-php-sdk, state

Solution

So how can I utilize the state-value to log a user into facebook and prevent CSRF?

This is being automatically handled by the Facebook PHP SDK. If you were about to write your own API calls to Facebook, you would need to submit the `state` manually (if desired) as per Facebook's `OAuth` documentation.

When you create a login url with `BaseFacebook::getLoginUrl()`, the first thing the function does is to establish CSRF token state1, which creates a hash using PHP's core `mt_rand()`, `uniqid()` and `md5()` functions and also stores the value as a session variable.

When the user gets redirected back to your page the, FBSDK checks if the submitted `state` matches the `state` value in the session. If the values indeed match, the `state` is cleared from the `Facebook` object and from the session, so all subsequent `getLoginUrl()` requests would get a new `state` variable.2

Theoretically you could use your own `state` value with FBSDK by writing it to `fb_<your_app_id>_state` session variable before constructing the `Facebook`-object, as the `BaseFacebook`'s constructor and `establishCSRFTokenState()` both check if the `state` already exists in the session.

But that would probably introduce more complexity than is necessary.

- see `BaseFacebook::establishCSRFTokenState()`

- see `BaseFacebook::getCode()`

Problem

I am using the PHP SDK getLoginUrl() function which works perfectly to log the user in. Once the user is redirected back to my page, the URL can come in two forms, see in the following link subsection 3: http://developers.facebook.com/docs/authentication/server-side/ Part of the return URL is a ?state= value. This value is supposed to be used to prevent Cross Site Request Forgery: http://developers.facebook.com/docs/reference/dialogs/oauth/ Though, using the getLoginUrl() method I can never set a state value as it is not one of the parameters: http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/ So how can I utilize the state-value to log a user into facebook and prevent CSRF?

Original source