2012-01-30 22 views
2

它看起来像Facebook发送时的验证位code,state参数通过$ _GET不包含在PHP-SDK中。

if(!empty($_GET['code']) && !empty($_GET['state'])) 
{ 
    $response = file_get_contents('https://graph.facebook.com/oauth/access_token?' . http_build_query(array('client_id' => AY_FACEBOOK_APP_ID, 'client_secret' => AY_FACEBOOK_APP_SECRET, 'redirect_uri' => AY_FACEBOOK_TAB_URL, 'code' => $_GET['code']))); 

    // now check state and parse access token 

    ay($response); 
} 

我忽略了什么吗?如果不是,那么不包括它的原因是什么?


请注意,我没有要求提供一个DMCS和Luc Franken迄今为止的例子。

回答

-1
$response = file_get_contents(
    'https://graph.facebook.com/oauth/access_token?' . http_build_query(
     array(
      'client_id' => AY_FACEBOOK_APP_ID, 
      'client_secret' => AY_FACEBOOK_APP_SECRET, 
      'redirect_uri' => AY_FACEBOOK_TAB_URL, 
      'code' => $_GET['code'] 
     ) 
    ) 
); 

// now check state and parse access token 

ay($response); 

这读起来好一点。现在

你的问题:这只是工作: https://graph.facebook.com/oauth/access_token?client_id=1&client_secret=2&redirect_uri=3&code=1234

有了这个测试代码:

echo 'https://graph.facebook.com/oauth/access_token?' . http_build_query(
     array(
      'client_id' => 1, 
      'client_secret' => 2, 
      'redirect_uri' => 3, 
      'code' => '1234' 
     ) 

); 

尝试把URL中的变量,这将使调试时的生活更轻松。

如果代码=部分中没有任何内容,那么您可能会在$ _GET ['code']变量中获取值,该变量将不会被http_build_query接受,因为该函数urlen代码数组数据。

+0

请再次阅读问题。 – Gajus 2012-01-30 18:43:49

2

是的,在关于CSRF保护的部分http://developers.facebook.com/docs/authentication/上讨论了状态和代码参数。

<?php 

    $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 = "http://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."); 
    } 

?> 
+1

请再次阅读该问题。 – Gajus 2012-01-30 18:44:05

+1

你问是否记录了有'state'的原因。我不仅为您提供了链接到您的文档的链接,我还在其中发布了包含该信息的代码段。 – DMCS 2012-01-30 18:50:20

+2

道歉,直接从代码开始,因为它不是很可读,现在读了3次后就知道了。 – 2012-01-30 18:50:42