CSRF保护如何工作? [英] How does this CSRF protection work?

查看:90
本文介绍了CSRF保护如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是来自Facebook身份验证页面的示例。将数据添加到会话,然后使用javascript重定向到URL的背后的想法是什么?另外,为什么要对uniqid进行md5哈希处理呢?

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

 ?>


推荐答案

我知道这很可能会定下来,因为它是Wikipedia链接,但您可以在 http://en.wikipedia.org/上找到csrf的完整说明。 Wiki / Cross-site_request_forgery ,一旦您完全了解了它是什么,您将了解如何为每个用户拥有一个唯一的令牌来保护它。预防部分列出了使用每用户令牌作为预防方法。

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.

这篇关于CSRF保护如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆