Facebook API – saving OAuth access token in session-Collection of common programming errors

I am trying to find a way to keep connected with the Facebook API once authorised using OAuth but am having problems. I dont want the users of my App to have to login via Facebook every time they want to use my app.

I store the oauth access toekn in a database after the user authenticates with facebook and I have "offline_access" permissions set, so in theory, this should be possible.

However, I get "Uncaught OAuthException: An active access token must be used to query information about the current user." when trying to connect to Facebook API using a saved Oauth token stored in a database.

header("p3p: CP=\"ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV\""); // hack to stop facebook wierd cookie problems

//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
    'appId' => 'appid',
    'secret' => 'secretid',
    'cookie' => true
));

//Get the FB UID of the currently logged in user
$user = $facebook->getUser();

//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) { 
    //get the user's access token
    $access_token = $facebook->getAccessToken();
} else  {
    //see if authorisation already set up in DB
    $query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND clientID = '$clientID'");  
    $result = mysql_fetch_row($query); 
    $access_token = $result[0];
}

if($access_token) { 

    //check permissions list
    $permissions_list = $facebook->api(
        '/me/permissions',
        'GET',
        array(
            'access_token' => $access_token
        )
    );

    //check if the permissions we need have been allowed by the user
    //if not then redirect them again to facebook's permissions page
    $permissions_needed = array('publish_stream', 'read_stream', 'offline_access');
    foreach($permissions_needed as $perm) {
        if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
            $login_url_params = array(
                'scope' => 'publish_stream,read_stream,offline_access',
                'fbconnect' =>  1,
                'display'   =>  "page",
                'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
            );
            $login_url = $facebook->getLoginUrl($login_url_params);
            header("Location: {$login_url}");
            exit();
        }
    }

    //if the user has allowed all the permissions we need,
    //get the information about the pages that he or she managers
    $accounts = $facebook->api(
        '/me',
        'GET',
        array(
            'access_token' => $access_token
        )
    );

    //add to details database
    //find the user by ID  
    if ($user != ''){
        $query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");  
        $result = mysql_fetch_array($query);  

        // If does not exist add to database  
        if(empty($result)){  
            $query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, clientID, oauth_uid, username, oauth_token, oauth_secret) VALUES ('facebook', $clientID, $user, '{$accounts['name']}', '$access_token', '')"); 
            $query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());  
            $result = mysql_fetch_array($query);  
        } else {  
            //update the tokens  
            $query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '$access_token', oauth_secret = '' WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");  
        }   


    //save the information inside the session
    $_SESSION['_token'] = $access_token;
    $_SESSION['accounts'] = $accounts['data'];
    }
    $facebookAuth = TRUE;
  1. Facebook pass an expires field when it pass your application the access token and default as per the Facebook is 2hours.

    there are other factors why which a access_token can expire and here are the complete details for you

    Ankur Pansari How-To: Handle expired access tokens

    Now next we can talk about offline_access which means

    It Enables your app to perform authorized requests 
    on behalf of the user at any time. By default, 
    most access tokens expire after a short time period to ensure applications 
    only make requests on behalf of the user when the are actively 
    using the application. This permission makes the 
    access token returned by our OAuth endpoint long-lived.
    

    So it all means you have to make sure you always using valid access_token.For details about various permission here is a reference link

    Facebook Permissions

Originally posted 2013-11-27 12:26:24.