【问题标题】:Facebook API - saving OAuth access token in sessionFacebook API - 在会话中保存 OAuth 访问令牌
【发布时间】:2012-01-18 10:29:02
【问题描述】:

我正在尝试找到一种方法来在使用 OAuth 获得授权后与 Facebook API 保持连接,但我遇到了问题。我不希望我的应用程序的用户每次想要使用我的应用程序时都必须通过 Facebook 登录。

在用户通过 facebook 进行身份验证并且我设置了"offline_access" 权限后,我将 oauth 访问 toekn 存储在数据库中,所以理论上这应该是可能的。

但是,当我尝试使用存储在数据库中的已保存 Oauth 令牌连接到 Facebook API 时,我得到了"Uncaught OAuthException: An active access token must be used to query information about the current user."

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;

【问题讨论】:

    标签: facebook-graph-api oauth access-token


    【解决方案1】:

    Facebook 在向您的应用程序传递访问令牌时传递一个 expires 字段,并且根据 Facebook 的默认值为 2 小时。

    还有其他因素导致 access_token 过期,这里是为您提供的完整详细信息

    Ankur Pansari How-To: Handle expired access tokens

    接下来我们可以谈谈offline_access,这意味着

    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.
    

    所以这一切都意味着您必须确保您始终使用有效的access_token。有关各种权限的详细信息,请参阅参考链接

    Facebook Permissions

    【讨论】:

    • 你确定你在使用主动 access_token 吗?
    • 我已经集成了来自“Ankur Pansari How-To:处理过期的访问令牌”的代码,明天我尝试在不登录的情况下更新状态时看看这是否有效。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-11-07
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2016-07-20
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多