简体   繁体   English

Facebook访问令牌 - 服务器端身份验证

[英]Facebook Access Tokens - Server-Side Authentication

Hello i'm trying to use facebook server-side authenticaion to get the access token but keep getting errors thrown at me. 您好我正在尝试使用Facebook服务器端身份验证来获取访问令牌,但不断向我发送错误。

I am using the bellow: 我正在使用下面的声音:

$app_id = "YOUR_APP_ID";
   $app_secret = "YOUR_APP_SECRET";
   $my_url = "YOUR_URL";

   session_start();
   $code = $_REQUEST["code"];

   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'];

     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

   if($_REQUEST['state'] == $_SESSION['state']) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = "https://graph.facebook.com/me?access_token=" 
       . $params['access_token'];

     $user = json_decode(file_get_contents($graph_url));
     echo("Hello " . $user->name);
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }

App ID and APP Secret have been removed so dont worry about that part. 已删除App ID和APP Secret,因此不必担心该部分。 I get errors about the get_file_contents time out. 我得到关于get_file_contents超时的错误。

[function.file-get-contents]: failed to open stream: Connection timed out [function.file-get-contents]:无法打开流:连接超时

Is there another or better way of getting the access tokens? 是否有另一种或更好的获取访问令牌的方法?

Bellow is the version i have tried including the cURL idea: 贝娄是我试过的版本,包括cURL的想法:

function get_data_cURL($url)
{
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

function getAccessToken(){
    $app_id = FB_APP_ID;
    $app_secret = FB_SECRET_ID;
    $canvas_URL = FB_CANVAS_URL;

    session_start();
    $code = $_REQUEST["code"];

    if(empty($code)) {
      $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
      $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
        . $app_id . "&redirect_uri=" . urlencode($canvas_URL) . "&state="
        . $_SESSION['state'];

      echo("<script> top.location.href='" . $dialog_url . "'</script>");
    }

    if($_REQUEST['state'] == $_SESSION['state']) {
      $token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_URL)
        . "&client_secret=" . $app_secret . "&code=" . $code;

     $returned_content = get_data_cURL($token_url);
    echo'Well Done! - '.$returned_content;

    }
    else {
      echo("The state does not match. You may be a victim of CSRF.");
    }
}

Details: 细节:

App Settings - Canvas URL: http://www.apps.elistone.co.uk/DrawMyFriend/ 应用程序设置 - 画布URL: http//www.apps.elistone.co.uk/DrawMyFriend/

FB_APP_ID = The Facebook App ID
FB_SECRET_ID = The Facebook Secret ID
FB_CANVAS_URL = http://www.apps.elistone.co.uk/DrawMyFriend/

Even with this update i still get this error: 即使有这个更新我仍然会收到此错误:

Old ERROR 旧错误

Well Done! 做得好! - {"error":{"message":"Error validating verification code.","type":"OAuthException","code":100}} - {“error”:{“message”:“验证验证码时出错。”,“type”:“OAuthException”,“code”:100}}

New ERROR 新的错误

This seems to be caused by the redirect removing the state code. 这似乎是由重定向删除状态代码引起的。

The state does not match. 国家不匹配。 You may be a victim of CSRF. 您可能是CSRF的受害者。 - 193c791ddd71c3fd84d411db5554c315 (state code) - 193c791ddd71c3fd84d411db5554c315(州代码)

I have also tried bypassing the CSRF protection by changing: 我还尝试通过更改来绕过CSRF保护:

if($_REQUEST['state'] == $_SESSION['state'])

TO: 至:

 if(!empty($code))

But this still gives the old error problem, I have heard it is caused by something in the redirect link but im not sure how to fix it. 但这仍然给出了旧的错误问题,我听说它是​​由重定向链接中的某些东西引起的,但我不知道如何修复它。

PROBLEM SOLVED 问题解决了

After trying along time i have resulted to using the PHP SDK using the below to get the user access token: 经过一段时间的尝试后,我使用下面的PHP SDK来获取用户访问令牌:

$app_id = FB_APP_ID;
$app_secret = FB_SECRET_ID;
$canvas_URL = FB_PAGE_URL;
$code = $_REQUEST["code"];

if(empty($code)) {
  $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
  $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
    . $app_id . "&redirect_uri=" . $canvas_URL . "&state="
    . $_SESSION['state'];

  echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$facebook->api('oauth/access_token', array(
    'client_id'     => FB_APP_ID,
    'client_secret' => FB_SECRET_ID,
    'type'          => 'client_cred',
    'code'          => $code,
));
$token = $facebook->getAccessToken();
echo$token;
}

I am now going to turn this into some sorta function. 我现在要将其变成某种功能。 Thank you very much for everyones time and help. 非常感谢大家的时间和帮助。

Hope this helps people in need in the future (unless Facebook changes everything suddenly) 希望这有助于将来有需要的人(除非Facebook突然改变一切)

I recommend you to use PHP SDK library for communicating with Facebook API. 我建议您使用PHP SDK库与Facebook API进行通信。 And simply use getAccessToken() or getAccessTokenFromCode() methods. 只需使用getAccessToken()getAccessTokenFromCode()方法即可。

UPDATE UPDATE

To retrieve user access token you have to send oauth request before getting access token. 要检索用户访问令牌,您必须在获取访问令牌之前发送oauth请求。 Details in answer update: 答案更新详情:

    $facebook->api('oauth/access_token', array(
        'client_id'     => APP_ID,
        'client_secret' => APP_SECRET,
        'type'          => 'client_cred',
        'code'          => $code,
    ));
    $token = $facebook->getAccessToken();

Two most likely causes of failure at this step are: 此步骤中两个最可能的失败原因是:

  • redirect_uri is missing the trailing '/' redirect_uri缺少尾随'/'
  • redirect_uri in your call to /oauth/access_token doesn't EXACTLY match the redirect_uri you provided to the oauth dialog redirect_uri在调用/oauth/access_token不完全匹配您的OAuth的对话框提供的REDIRECT_URI

In either case, the code verification will fail and you won't get a token, 在任何一种情况下,代码验证都会失败,您将无法获得令牌,

The 'failed to open stream: Connection timed out' error probably isn't related to that though, it usually points to a DNS or network error when trying to reach graph.facebook.com from your server “无法打开流:连接超时”错误可能与此无关,但是当尝试从服务器访问graph.facebook.com时,通常会指向DNS或网络错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM