Facebook OAuth: custom callback_uri parameters

Viewed 53853

I'd like to have a dynamic redirect URL for my Facebook OAuth2 integration. For example, if my redirect URL is this in my Facebook app:

http://www.mysite.com/oauth_callback?foo=bar

I'd like the redirect URL for a specific request be something like this, so that on the server, I have some context about how to process the auth code:

http://www.mysite.com/oauth_callback?foo=bar&user=6234

My redirect gets invoked after the authorization dialog is submitted, and I get back an auth code, but when I try to get my access token, I'm getting an OAuthException error back from Facebook. My request looks like this (line breaks added for clarity):

https://graph.facebook.com/oauth/access_token
    ?client_id=MY_CLIENT_ID
    &redirect_uri=http%3A%2F%2Fwww.mysite.com%2Foauth_callback%3Ffoo%3Dbar%26user%3D6234
    &client_secret=MY_SECRET
    &code=RECEIVED_CODE

All of my parameters are URL-encoded, and the code looks valid, so my only guess is that the problem parameter is my redirect_uri. I've tried setting redirect_uri to all of the following, to no avail:

  1. The actual URL of the request to my site
  2. The URL of the request to my site, minus the code parameter
  3. The URL specified in my Facebook application's configuration

Are custom redirect URI parameters supported? If so, am I specifying them correctly? If not, will I be forced to set a cookie, or is there some better pattern for supplying context to my web site?

6 Answers

You should set your custom state parameter using the login helper as such:

use Facebook\Facebook;
use Illuminate\Support\Str;

$fb = new Facebook([
    'app_id' => env('FB_APP_ID'),
    'app_secret' => env('FB_APP_SECRET'),
    'default_graph_version' => env('FB_APP_VER'),
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = [
    'public_profile',
    'user_link',
    'email',
    'read_insights',
    'pages_show_list',
    'instagram_basic',
    'instagram_manage_insights',
    'manage_pages'
];

$random = Str::random(20);

$OAuth2Client = $fb->getOAuth2Client();

$redirectLoginHelper = $fb->getRedirectLoginHelper();

$persistentDataHandler = $redirectLoginHelper->getPersistentDataHandler();

$persistentDataHandler->set('state', $random);

$loginUrl = $OAuth2Client->getAuthorizationUrl(
        url('/') . '/auth/facebook',
        $random,
        $permissions
    );

Hey if you are using official facebook php skd then you can set custom state param like this

$helper = $fb->getRedirectLoginHelper();
$helper->getPersistentDataHandler()->set('state',"any_data");
$url = $helper->getLoginUrl($callback_url, $fb_permissions_array);
Related