James P.
James P.

Reputation: 19617

How does this CSRF protection work?

The following is an example taken from Facebook's authentication page. What is the idea behind adding data to the session and then redirecting to a URL using javascript? Also why do an md5 hash of a uniqid?

<?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.");
   }

 ?>

Upvotes: 4

Views: 3508

Answers (3)

hoppa
hoppa

Reputation: 3041

By generating a hard (impossible) to guess value ans storing it in a session as well as sending it with a request, this script can verify if it was called by itself instead of somewhere else. somewhere else the hard to guess value would be unknwon and could thus not be supplied.

Upvotes: 1

Femi
Femi

Reputation: 64710

It ensures that you are being redirected here only in response to an action initiated by the site. Read up on CSRF at https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29.

Upvotes: 1

Liam Bailey
Liam Bailey

Reputation: 5905

I know this will probably get slated as it is a wikipedia link, but you can find a full explanation of csrf here http://en.wikipedia.org/wiki/Cross-site_request_forgery, once you fully understand what it is you will understand how having a unique token per user can protect against it. The prevention section lists using a per-user token as a method of prevention.

Upvotes: 3

Related Questions