2012-01-25 7 views
0

「次のPHPの例では、CSRF保護機能を備えたサーバー側のフローを、自己完結型の1つの例で示しています。」と表示されています。http://developers.facebook.com/docs/authentication/です。 なぜsession_start();必要ですか?私は、セッションの作業がどこで開始されるのか終了するのか分かりません。 CSRFの保護はどのように機能しますか? ユーザーログイン直後にアクセストークンが返されないのはなぜですか?Facebook認証でセッションが始まる場所はどこですか?

+0

関連質問:http://stackoverflow.com/questions/6656097/how-does-this-csrf-protection-work – PiTheNumber

答えて

1

あなたはスクリプトの一番上に一度、それが印刷される前に一度電話をかけます。

その後、$_SESSIONアレイにアクセスできます。これにより、$_SESSION['state']のような値をあるページ呼び出しから別のページ呼び出しに格納することができます。

この例のコードは、CSRF protectionです。最初にttを呼び出すと、セッションにランダムな値が格納され、その後で比較されます。

続きを読むphp sessionsを参照してください。

更新コメント付きのスクリプト。スクリプトの上にある画像を見ていると、そこからいくつかの点がマークされています。

// Set your facebook config here 
    $app_id = "YOUR_APP_ID"; 
    $app_secret = "YOUR_APP_SECRET"; 
    $my_url = "YOUR_URL"; 

    // start session to store random state 
    session_start(); 
    // get a code from the request 
    $code = $_REQUEST["code"]; 

    // if no code was send to the script... 
    if(empty($code)) { 
    // generate a random, unique id and store it the session 
    $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection 
    // create facebook dialog url 
    $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
     . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" 
     . $_SESSION['state']; 

    // redirect user to facebook 
    // Facebook login and App Permissions request 
    // "GET OAuth Dialog" 
    echo("<script> top.location.href='" . $dialog_url . "'</script>"); 
    } 

    // CSRF protection: check if state parameter is the same as 
    // we stored it in the session before the redirect 
    if($_REQUEST['state'] == $_SESSION['state']) { 
    // do facebook auth "GET /oauth/authorize" 
    $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); 

    // "GET me?access_token" 
    $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."); 
    } 
+0

ありがとう!なぜユーザーのログイン直後にアクセストークンが返されないのですか?それは実際に何をしていますか? –

+0

「facebook dialog」とは何ですか? –

+0

Facebookのログイン情報(必要な場合)とアプリのアクセス許可のリクエストが含まれています。ページの最初の2枚の写真に表示されています。 – PiTheNumber

関連する問題