2012-01-30 24 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