Codeigniter CSRF仅对ajax请求有效一次

rom*_*mio 10 php ajax jquery codeigniter csrf-protection

我想在jQuery的更改事件上上传服务器上的图像但是使用codeigniter csrf我只能上传图像一次.如何使用ajax为多个请求上传图像.请在设置时记住

config['csrf_protection'] = FALSE;
Run Code Online (Sandbox Code Playgroud)

然后我能够发送多个请求jQuery onchange事件,但是当csrf_protection将为false时,我认为没有csrf的优势.所以问题是如何在启用csrf_protection时使用ajax发送多个请求.我的jquery代码如下

$("#avatar").change(function(){
    var link = $("#avatar").val();     
    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',"id":"hello","link":link},            
        success : function(data)
        {   
            alert(data);
        }  
    });
});
Run Code Online (Sandbox Code Playgroud)

小智 16

在我看来,你应该尝试每个请求重新创建你的csrf令牌

试试这个代码示例......

对于js funcion

var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
    csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
("#avatar").change(function(){
    var link = $("#avatar").val();

    var dataJson = { [csrfName]: csrfHash, id: "hello", link: link };

    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: dataJson,            
        success : function(data)
        {   
            csrfName = data.csrfName;
            csrfHash = data.csrfHash;
            alert(data.message);
        }  
    });
});
Run Code Online (Sandbox Code Playgroud)

并为控制器

public function test() { 
    $config['upload_path'] = './uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = 500; 
    $config['max_width'] = 260; 
    $config['max_height'] = 260; 

    $reponse = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash()
                )

    $this->load->library('upload', $config); 
    if (!$this->upload->do_upload('link')) { 
        $reponse['message'] = "error"; 
    } 
    else { 
        $data = array('upload_data' => $this->upload->data()); 
        $image_name = $data['upload_data']['file_name']; 
        $reponse['message'] = $image_name; 
    } 

    echo json_encode($reponse);
}
Run Code Online (Sandbox Code Playgroud)

让我知道,祝你好运

注意:当有人要求您在问题中发布更多数据时,请不要将其作为评论或答案发布,最好编辑问题本身并添加内容


Elo*_*e85 5

您可以在config.php中设置

$config['csrf_regenerate'] = FALSE;
Run Code Online (Sandbox Code Playgroud)

因此,csrf保护在所有会话期间均有效,它将解决您的问题。如果设置, $config['csrf_regenerate'] = true;则CI每次请求都会生成新的csrf令牌,因此您的旧csrf令牌与新生成的csrf令牌不匹配

  • 我搜查了很多,可以说不建议使用这种方法,否则会造成安全性损失,还有其他方法。 (2认同)