How does this CSRF protection work?

The following is an example taken on the Facebook authentication page. What is the idea of ​​adding data to the session and then redirecting to the url using javascript? Also why is the md5 uniqid hash?

<?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."); } ?> 
+4
source share
3 answers

I know this will probably succeed, as this is a link to wikipedia, but you can find a full explanation of csrf here http://en.wikipedia.org/wiki/Cross-site_request_forgery as soon as you fully understand what it is , you will understand how the presence of a unique token per user can protect him. The enumeration prevention section uses a token for each user as a prevention method.

+3
source

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

+1
source

By creating a complex (impossible) guessing value of ans that stores it in a session and also sends it with a request, this script can check if it was called on its own, and not somewhere else. elsewhere it is difficult to guess a value that would be unknwon and therefore could not be provided.

+1
source

All Articles