codeigniter csrf与ajax无法在IE中工作

时间:2013-10-27 06:12:35

标签: jquery ajax codeigniter internet-explorer csrf

我的csrf启用了codeigniter,可以在FireFox和Google Chrome中正常使用。但是在IE中,它在Web开发人员工具网络面板中显示此错误:

enter image description here

并在详细视图中:

enter image description here

我的$.post来电是:

var ctn = $.cookie('csrf_cookie');
$.post('some_path', {
    'my_token': ctn
}, function (data) {
    if (data.res == 'something') {
        //process here
    }, 'json');
当我得到ctn时,

并且console.log('ctn: '+ctn)的值(即保存CSRF令牌值的cookie)会正确显示:

ctn: 78346b5d0ec105efcce796f93ecc3cbb 

非常感谢任何有关调试的帮助或建议。

P.S。:我有一个vhost,我真的不知道它是否会对IE产生影响。

更新

我已经阅读了IE中有关CSRF的问题,有人建议使用P3P标头,所以我将这个标题添加到索引页面:

header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT');

但仍有同样的问题。

还有其他建议吗?

2 个答案:

答案 0 :(得分:3)

正如我在my article中建议的那样。最好在net.tutsplus中使用标题为Protect a CodeIgniter Application Against CSRF的帖子。这是一篇旧帖子,解决方案适用于Codeignter 1.7.x.然而,对于Codeigniter 2来说,这是迄今为止我能找到的唯一合适的解决方案,以便在Codeigniter中实现CSRF保护。我们这里的主要问题是Codeigniter使用COOKIE。然而,这篇文章使用了Codeigniter会话,它使用起来更安全,它适用于所有浏览器而没有任何问题。 net.tutsplus中的文章适用于AJAX和非AJAX请求。

所以我的建议是,如果您找不到解决问题的方法,可以尝试实施该文章:Protect a CodeIgniter Application Against CSRF

答案 1 :(得分:2)

感谢 @John 建议我自己实施CSRF,我通过了第一期。然而,事实证明IE根本没有提交帖子数据(在调试之后)所以,有一个关于stackoverflow的问题,标题为IE is refusing to send data through $.ajax 要解决这个问题,你必须添加这个meta标签,告诉IE在IE9兼容模式下使用javascript。

<meta http-equiv="x-ua-compatible" content="IE=9" >

现在,关于使用钩子解决csrf的文章,它错过了一个问题,即如果你使用.serializeArray()或jquery中的任何等价物来提交表单,你需要修改
validate_tokens函数用于检查已发布数组中的token_name

希望这可以拯救有同样问题的人

注意:添加元标记而不重写csrf将无法解决问题。

更新1:

以下是我正在使用的实现:

<?php
/**
 * Description of csrf_protection
 * @author Ian Murray
 */
class Csrf_Protection {

    private $CI;
    private static $token_name = 'somename';
    private static $token;

    public function __construct() {
        $this->CI = &get_instance();
    }

/** 
 * Generates a CSRF token and stores it on session. Only one token per session is generated. 
 * This must be tied to a post-controller hook, and before the hook 
 * that calls the inject_tokens method(). 
 * 
 * @return void 
 * @author Ian Murray 
 */ 
    public function generate_token()  
    {  
          // Load session library if not loaded  
          $this->CI->load->library('session');  

          if ($this->CI->session->userdata(self::$token_name) === FALSE)  
          {  
            // Generate a token and store it on session, since old one appears to have expired.  
            self::$token = md5(uniqid() . microtime() . rand());

            $this->CI->session->set_userdata(self::$token_name, self::$token);  
          }  
          else  
          {  
            // Set it to local variable for easy access  
            self::$token = $this->CI->session->userdata(self::$token_name);  
          }  
    }  

    /** 
    * Validates a submitted token when POST request is made. 
    * 
    * @return void 
    * @author Ian Murray 
    */  
   public function validate_tokens()  
   {  
     // Is this a post request?  
     if ($_SERVER['REQUEST_METHOD'] == 'POST')  
     {  
       // Is the token field set and valid?  
       $posted_token = $this->CI->input->post(self::$token_name);  
       if($posted_token === FALSE){
           $posted_token = $this->_get_token_in_post_array($this->CI->input->post());
           $this->_check_all_post_array($posted_token);
       }
     }  
   }
   /**
   *takes the posted token and check it after multidimesional-array search
   *@params $posted_token
   *@author Mamdouh Alramadan
   */
   private function _check_all_post_array($posted_token)
   {
       if ($posted_token === 'error' || $posted_token != $this->CI->session->userdata(self::$token_name))  
       {  
         // Invalid request, send error 400.
         show_error('Request was invalid. Tokens did not match.', 400);  
       }  
   }


   /** 
    * This injects hidden tags on all POST forms with the csrf token. 
    * Also injects meta headers in <head> of output (if exists) for easy access 
    * from JS frameworks. 
    * 
    * @return void 
    * @author Ian Murray 
    */  
   public function inject_tokens()  
   {  
     $output = $this->CI->output->get_output();  

     // Inject into form  
     $output = preg_replace('/(<(form|FORM)[^>]*(method|METHOD)="(post|POST)"[^>]*>)/',  
                            '$0<input type="hidden" name="' . self::$token_name . '" value="' . self::$token . '">',   
                            $output);  

     // Inject into <head>  
     $output = preg_replace('/(<\/head>)/',  
                            '<meta name="cname" content="' . self::$token_name . '">' . "\n" . '<meta name="cval" content="' . self::$token . '">' . "\n" . '$0',   
                            $output);  

     $this->CI->output->_display($output);  
   }  


/**
 * takes the posted array and check for the token inside it 
 * @params $arr array
 * @author Mamdouh Alramadan
 */
   private function _get_token_in_post_array($arr)
   {//this function is customized to my case but it's easy to adapt
       if(is_array($arr)){
        $key = $this->_recursive_post_array_search(self::$token_name, $arr);//this will return data if token found
        if($key === 'data'){//I'm expecting the token inside data array
            $key = $this->_recursive_post_array_search(self::$token_name, $arr['data']);
            return isset($arr['data'][$key]['value'])?$arr['data'][$key]['value']:FALSE;
        }
       }
       return 'error';
   }
   //some custom function to do multi-dimensional array search, can be replaced with any other searching function.
   private function _recursive_post_array_search($needle,$haystack) {
        foreach($haystack as $key=>$value) {
            $current_key=$key;
            if($needle===$value OR (is_array($value) && $this->_recursive_post_array_search($needle,$value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

}

?>